如何在 Angular 8 或 9 中发出同步 HTTP 请求(发出请求并等待) [英] How to make synchronous HTTP request in Angular 8 or 9 (make a request and wait)
问题描述
共有三个按钮:
点击第一个 Request HTTP Data As Promise
按钮会得到它作为 Promise
的 HTTP 响应.
Clicking the first Request HTTP Data As Promise
button gets its HTTP response as a Promise
.
第二个 Request HTTP Data As Observable
按钮将其响应作为 Observable
.
The second Request HTTP Data As Observable
button gets its response as an Observable
.
这两个按钮都使用异步响应机制获得响应.
Both these buttons get their responses using asynchronous response mechanism.
现在,我希望第三个 Request HTTP Data and Wait
按钮获得同步响应.我希望它等待 http 服务返回 HTTP 响应.
Now, I would like the third Request HTTP Data and Wait
button to get a synchronous response. I would like it to wait for the http service to return the HTTP response.
怎么可能做到?这是 Stackblitz 项目的链接(请使用 HttpService
脚本中定义的占位符函数 getDataSynchronous
来实现此功能):
How could it be done? Here is the link to the Stackblitz project (please use the placeholder function getDataSynchronous
defined in the HttpService
script to implement this functionality):
https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts
export class HttpService {
jsonFile = '../assets/products.json';
constructor(private http: HttpClient) {}
getDataAsPromise(): Promise<any> {
return this.http.get(this.jsonFile)
.toPromise()
}
getDataAsObservable(): Observable<any> {
return this.http.get(this.jsonFile)
}
getDataSynchronous(): any {
return []
}
推荐答案
Demo异步函数是通过事件循环异步操作的函数,使用隐式 Promise 返回其结果.但是使用异步函数的代码的语法和结构更像是使用标准同步函数.await 运算符用于等待 Promise.它只能在异步函数中使用.
Demo An asynchronous function is a function that operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions are much more like using standard synchronous functions. The await operator is used to wait for a Promise. It can only be used inside an async function.
getDataSynchronous() {
return this.http.get(this.jsonFile).toPromise()
}
在组件中
async requestDataAndWait() {
let httpData = await this.http.getDataSynchronous();
this.addMessages(httpData)
}
这篇关于如何在 Angular 8 或 9 中发出同步 HTTP 请求(发出请求并等待)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!