Angular RXJS的API调用工作不正常

Angular RXJS的API调用工作不正常,angular,rxjs,Angular,Rxjs,我有组件和服务。组件正在调用正在创建API调用的服务函数。 一旦API调用完成,我想调用另一个函数并传递API调用的结果。 技术:angular、rxjs、swagger 在组件中: of(this.customerService.getCustomerOverview(this.id)).subscribe((x)=>{ console.log(x); this.getResultValues(x); }); 在职: getCustomerOvervie

我有组件和服务。组件正在调用正在创建API调用的服务函数。 一旦API调用完成,我想调用另一个函数并传递API调用的结果。 技术:angular、rxjs、swagger

在组件中:

of(this.customerService.getCustomerOverview(this.id)).subscribe((x)=>{
      console.log(x);
      this.getResultValues(x);
    });
在职:

getCustomerOverview(id) {
    this.localSubscriptions.push(this.apiClient.getCustomer(id, '').subscribe(result => {
      console.log(result);
      return result;
    },
      (error: any) => {

      }));
  }
错误: this.getResultValue(x)的值;在API调用完成之前调用,结果返回调用函数


谢谢你的帮助

如果我是你,我会:

// service
import { BehaviorSubject } from 'rxjs';
....
public customerCache$: BehaviorSubject<any> = new BehaviorSubject(null);
getCustomerOverview(id) {
  return this.apiClient.getCustomer(id, '');
}
.....
// component
import { of } from 'rxjs;
import { switchMap, take } from 'rxjs/operators';
.....
this.customerService.customerCache$.pipe(
  // take(1) to kill the subscription after the subscribe, I am scared of an infinite loop because of the .next in the subscribe
  take(1),
  switchMap(cache => {
     // if the cache is truthy, great, use it
     if (cache) {
       return of(cache);
     } else {
       // else make an API call
       return this.customerService.getCustomerOverview(this.id);
     }
  }),
).subscribe(x => {
  // store x as the cache
  this.customerService.customerCache$.next(x);
  // make sure this console doesn't log infinitely
  console.log(x);
  this.getResultValues(x);
});
//服务
从“rxjs”导入{BehaviorSubject};
....
public customerCache$:BehaviorSubject=新的BehaviorSubject(null);
getCustomerOverview(id){
返回此.apiClient.getCustomer(id为“”);
}
.....
//组成部分
从rxjs导入{of};
从“rxjs/operators”导入{switchMap,take};
.....
这个.customerService.customerCache$.pipe(
//采取(1)在订阅之后终止订阅,我害怕无限循环,因为订阅中的.next
以(1)为例,
开关映射(缓存=>{
//如果缓存是真实的,很好,就使用它
如果(缓存){
返回(缓存);
}否则{
//否则进行API调用
返回this.customerService.getCustomerOverview(this.id);
}
}),
).订阅(x=>{
//将x存储为缓存
this.customerService.customerCache$.next(x);
//确保此控制台不会无限记录
控制台日志(x);
这个.getResultValue(x);
});
无需在Angular中取消订阅
http
调用,因为它们是有限的


现在,在需要从中读取值的任何其他地方,都可以从缓存中读取该值,与此类似。我不喜欢这个,因为我会使用Ngrx。继续以这种方式创建意大利面代码。

Angular有一个内置的http客户端,它返回一个可观察的。我建议看一看他们的例子,因为你做这件事的方式比应该的复杂得多。实际上,这只是一个你不能从订阅中返回的问题。删除subscribe并返回一个observable。然后还可以删除()的。请记住,您不能从订阅返回,您可以从节点经典回调返回。谢谢。这是我以前使用过的场景。这个场景的一个问题是,如果我想再次调用该API的结果。假设我第一次调用了API,并将数据分配给变量getCustomerOverview(id){if(!this.customerOverview){this.customerOverview=this.apiClient.getCustomer(id');}返回this.customerOverview;}我的变量是可观察的,无论如何它创建了一个API调用。您将如何解决这个问题?如果您已经调用了服务,您希望不调用该服务吗?我希望调用该服务,但如果数据存在,则不希望第二次调用API。但是,我的变量是可观察的,并且无论如何都会调用API。我在网络上看到了,你能不能用
if
语句来做?查看我的编辑。它正在工作。好办法!谢谢然而,如果有一个Rxjs解决方案来解决这个问题,也就是说,调用服务并返回observable,而不调用API,这是多么有趣的事情。然而,您的解决方案是一个很好的工作版本。