等待 HttpClient get 的响应 - 同步调用

Wait for response from HttpClient get - synchronous call

我想知道如何等待调用后端的 HttpClient 操作的响应,我的需要是等到后端 returns 给出响应(同步调用),经典方法是订阅对 Observable 响应:

//My component
...
console.log("before");
this.myService.getSomeThingFromBackend('param_value').subscribe(response => {
     console.log("do my stuff");
}
console.log("after");

//My Service
...
getSomeThingFromBackend(param: string): Observable<any>{
        return this.httpClient.get(this.host + this.url+ "/" + param);
}

这表明:

before

after

do my stuff

我想要这个结果:

before

do my stuff

after

因为听起来很明显的风险...如果你想一个接一个地执行一个动作,然后移动在错误位置的动作。

//My component
...
console.log("before");
this.myService.getSomeThingFromBackend('param_value').subscribe(response => {
  console.log("do my stuff");
  console.log("after");
}

//My Service
...
getSomeThingFromBackend(param: string): Observable<any> {
  return this.httpClient.get(this.host + this.url+ "/" + param);
}

您所做的其他一切都很好。您正在从服务返回可观察对象,在组件中订阅它,并且 运行 订阅中的一个动作。

这个过程异步工作,所以你不能让它等待其他东西,直到它们在响应范围内。您可以在同一范围内编写这些调用或创建一个函数并从内部调用它。

//My component

...
console.log("before");
this.myService.getSomeThingFromBackend('param_value').subscribe(response => {
     console.log("do my stuff");
     doSomeStuff();
}

doSomeStuff(){
    console.log("after");
}

//My Service
...
getSomeThingFromBackend(param: string): Observable<any>{
        return this.httpClient.get(this.host + this.url+ "/" + param);
}

Angular 的 this.http.get return 是一个 RxJS Observable。然后调用 this.http.get(...).subscribe(...) returns RxJS Subscription 对象。所以 none 其中 return Promise 所以你不能将它们与 await.

一起使用

如果你希望能够将 await 与 Observables 一起使用,你必须使用 toPromise() 而不是 subscribe(),return 是一个由第一个解决的 Promise该 Observable 发出的值(它在内部为您调用 subscribe 并用 Promise 对象包装它)。

await this.http.get(...).toPromise(value => {
  ...
});

您可能不想在这种情况下使用 HttpClient。 使用同步 http 请求如下

var request = new XMLHttpRequest();
request.open('GET', "https://domain/api", false);  
request.send(null);
const response = JSON.parse(request.responseText); 

使用 HttpClient 将无法利用 DI,因此应在需要时绝对使用。