📜  angular http async false - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:23.498000             🧑  作者: Mango

Angular HTTP同步请求 (async: false)

当我们使用 Angular 中的 HttpClient 来进行 Ajax 请求时,默认情况下所有的请求都是异步的。但是,有时我们需要发出一个同步请求,直到获取到响应后再进行后续操作。这时就可以使用 async:false 参数来发出同步请求。

使用方法
import { HttpClient } from '@angular/common/http';

@Component({
  // ...
})
export class MyComponent {
  constructor(private http: HttpClient) {}

  getData() {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    const options = {
      observe: 'response',
      responseType: 'json',
      async: false   // 设置同步请求
    };

    const response = this.http.get(url, options);
    console.log(response);
    // 同步请求会阻塞线程,直到返回结果
    // 继续执行下面的代码
  }
}
注意事项
  • 避免在 UI 线程上进行同步请求,因为同步请求会阻塞 UI 线程,导致页面卡顿或者无响应。
  • 同步请求可能会导致死锁。当请求的 URL 在服务端被重定向时,如果你没有处理好重定向,就会导致死锁。
  • 同步请求已经在最新的浏览器标准中被废弃,不建议使用。

Angular HTTP Sync Requests (async: false)

When we use the HttpClient in Angular to make AJAX requests, by default all requests are asynchronous. However, there are times when we need to make a synchronous request and wait for the response before proceeding with further operations. In such cases, you can use the async: false parameter to make a synchronous request.

Usage
import { HttpClient } from '@angular/common/http';

@Component({
  // ...
})
export class MyComponent {
  constructor(private http: HttpClient) {}

  getData() {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    const options = {
      observe: 'response',
      responseType: 'json',
      async: false   // make synchronous request
    };

    const response = this.http.get(url, options);
    console.log(response);
    // Synchronous request will block the thread until result is returned
    // Continue executing the code below
  }
}
Notes
  • Avoid making synchronous requests on the UI thread as synchronous requests will block the UI thread causing the page to become unresponsive or laggy.
  • Synchronous requests can cause deadlocks. When the URL being requested is redirected on the server-side, if you don't handle the redirection correctly, it can cause a deadlock.
  • Synchronous requests have been deprecated in the latest browser standards and are not recommended.