Angular-多次订阅而不触发多个呼叫? [英] Angular - subscribe multiple times without firing multiple calls?

查看:40
本文介绍了Angular-多次订阅而不触发多个呼叫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务呼叫,其响应被缓存在我的Angular服务中,如下所示:

I have a service call, whose response is cached inside my Angular service like this:

public cacheMyServiceResponse(): Observable<any> {
  return this.appConfig.getEndpoint('myService')
    .pipe(
      switchMap((endpoint: Endpoint) => this.http.get(endpoint.toUrl())),
      tap((body: any) => {
        if (body) { //  this endpoint can also return a 204 (No Content), where body is null
          this.cache = body.myData;
        }
      }),
      take(1),
      catchError(error => {
        this.errorService.trackError(error.status);
        return of(true);
      })
    );
}

因此,我的http.get调用的响应将存储在一个名为"cache"的全局变量中.

So the response of my http.get call will be cached here, in a global variable called "cache".

问题是,此调用实际上可能响应得很晚,因此我们希望在页面加载时(初始化时)立即调用此端点.但是实际的响应,或者我们的呼叫是否结束(成功还是错误),只有在用户单击按钮时才需要此信息.当然,在单击按钮的那一刻,响应可能还没有出现,并且在在这种情况下,我要等待.(因此,我需要的不只是一个简单的布尔标志)

The problem is, this call may really response very late, so we wanted to call this endpoint as soon as our page loads (while initialization). But the actual response, or whether our call is finished (either success or error), we need this info only then when user clicks a button.. Of course at that moment of button click, the response may not be there yet, and in this case i would like to wait for it. (so i need more than a simple boolean flag)

所以我想像这样在ngOnInit中初始化此调用:

So i want to initialize this call in a ngOnInit like this:

ngOnInit() {
    this.myService.cacheMyServiceResponse().subscribe();
}

但是在其他地方,我需要知道它是否已经结束通话,而无需两次触发我的http通话.

But somewhere else i need to know if it is already finished the call, without firing my http call twice.

onClick() {
    this.myService.cacheMyServiceResponse().subscribe(() => {
       // call is finished..
    });
}

此刻,该服务将被调用两次.我该怎么办?

At the moment the service will be called twice. How can i do this?

PS:我没有故意进行错误处理,我只需要知道服务调用是否全部完成即可.

推荐答案

我建议使用 ReplaySubject() 并订阅 ReplaySubject() onClick,它将等待您的服务发出数据,同时仍然可以订阅它,即使它没有从服务中发出数据之前被订阅,您将不会丢失数据:

I suggest to use ReplaySubject() and subscribe to the ReplaySubject() onClick instead, it will wait for your service to emit data while it still can be subscribed to, also if it did not be subscribed before the data from service emit, you wont miss the data:

yourWaitingData = new ReplaySubject();
subscription;

ngOnInit() {
    this.myService.cacheMyServiceResponse().subscribe(res => {
        //yourWaitingData only emit when res is return from API call
        this.yourWaitingData.next(res)
    });
}

然后订阅它:

onClick() {
    if(this.subscription){
       this.subscription.unsubscribe()
    }
    this.subscription = this.yourWaitingData.subscribe((x) => {
       // subscribed and will wait for data to be emited from service
       console.log(x)
    });
}

这篇关于Angular-多次订阅而不触发多个呼叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆