📅  最后修改于: 2023-12-03 15:29:23.498000             🧑  作者: Mango
当我们使用 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);
// 同步请求会阻塞线程,直到返回结果
// 继续执行下面的代码
}
}
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.
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
}
}