简体   繁体   中英

"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. But i want to return the first value (the token)

Do i subscribe to inside the tap()? i guess not 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.

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
      )
    )
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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