简体   繁体   English

可观察到的“订阅”

[英]"subscription" in an observable

Let's say that I have this services假设我有这项服务

    export class CacheApiService {
    ...   
      updateTokenCache() {
        const url = `${this.consultationBaseURL}/cache/idm/updateTokenCache`;
        return this.httpClient.put<any>(url, {});
      }
    }

AND

export class CacheService {

    updateTokenCache() {
      return this.cacheApiService.updateTokenCache().pipe(
        catchError(err => throwError(err)),
        tap( res => {
          this.logger.info(`CacheService - updateTokenCache()`, res);
        })
      );
    }
}

whatever, this is not important不管怎样,这不重要

the issue is there: In an other service i have this method that returns a token问题就在那里:在另一个服务中,我有这个返回令牌的方法

refreshToken(): Observable<string> {

    this.logger.debug('refreshToken()');

    return this.impersonateUser().pipe(
      takeUntil(this.destroySubject$),
      tap( token => {
        this.logger.info('token', token);
        if (token) {
          this.refreshTokenState(token);
          this.storeUserPrincipal(token);
        }
      })
    );
  }

I want, once i get the token, set it in cache by calling the method updateTokenCache() from the CacheService, inside that Observable.我想,一旦我获得令牌,通过从该 Observable 内部的 CacheService 调用方法 updateTokenCache() 将其设置在缓存中。 But i want to return the first value (the token)但我想返回第一个值(令牌)

Do i subscribe to inside the tap()?我是否在 tap() 内订阅? i guess not this.cacheService.updateTokenCache().subscribe()我猜不是 this.cacheService.updateTokenCache().subscribe()

So i Cannot find a way to achieve this, and of course i want to do that inside that observable所以我找不到实现这一目标的方法,当然我想在那个可观察的范围内做到这一点

Thank you for your help谢谢您的帮助

You could use switchMap to cache the token and use map to return back the token instead of the response from the updateTokenCache() observable.您可以使用switchMap缓存令牌并使用map返回令牌而不是来自可观察的updateTokenCache()的响应。

refreshToken(): Observable<any> {
  this.logger.debug('refreshToken()');

  return this.impersonateUser().pipe(
    takeUntil(this.destroySubject$),
    tap(token => {
      this.logger.info('token', token);
      if (token) {
        this.refreshTokenState(token);
        this.storeUserPrincipal(token);
      }
    }),
    switchMap((token: any) => 
      this.cacheService.updateTokenCache(token).pipe(
        map(() => token)    // <-- send back the token here
      )
    )
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM