首页 > 解决方案 > 调用已订阅的方法如何等待订阅返回类型?

问题描述

所以我的问题希望相对容易解决。所以(Angular 8 btw)我调用了一个方法,并在该方法内部订阅了一个 api 调用。一切正常,除了返回总是在方法之后一两秒后被调用,并且返回类型永远不会正确返回。我尝试了 MAP,但它不能正常工作。让我编写一个简单的示例:

return this.callApi( apiObject ); // I want to wait for subscribe and return data here

callApi( apiObject ) {
  this.myApiService.someRandomPostApiCall( apiObject ).subscribe(res => {
            console.log(res);
            res.valid ? { return true } : { return false };
    });
}

标签: angularasynchronousrxjssubscription

解决方案


如果您想在发出项目时做出反应(基本上等到检索数据),最好的办法是在您需要它的组件中订阅,而不是在函数本身中订阅。

return this.callApi( apiObject ).subscribe(//do stuff here);

callApi( apiObject ) {
  return this.myApiService.someRandomPostApiCall( apiObject )
}

这是我的一个应用程序的示例:

在服务中

  getProducts(): Observable<IProduct[]> {
    return this.http.get<IProduct[]>(this.productUrl)
      .pipe(
        tap(data => console.log('All: ' + JSON.stringify(data))),
        catchError(this.handleError)
      );
  }

在一个组件中

  ngOnInit(): void {
    this.productService.getProducts().subscribe({
      next: products => this.products = products,
      error: err => this.errorMessage = err
    });
  }

您可以在此处查看整个源代码:

https://stackblitz.com/edit/github-angular-getting-started-final


推荐阅读