Return observable bit first get new token in Angular 11 / RxJS 7

I'm having a really rough time with Angular / RxJS trying to learn it under crazy pressure!

If I'm returning this Observable:

 return this.apiProvider.Tracker(parameters).map((res: any) => {
      let response = res.Result;
      return response;
  }).catch(error => {
      this.presentToast('An error has occurred. If this problem persists, please contact us.', false);
      let res: ConsentResponse = null
      return Observable.of(res);
  });

It works perfectly fine. The Tracker function is just a simple http.post return, like this:

Tracker(params) {

I NEED TO GET A NEW TOKEN HERE FIRST BY DOING ANOTHER POST REQUEST - and that is my question :-)
var auth = 'Bearer ' + localStorage.getItem("pptoken");
const requestHeaders = {
  'Authorization': auth,
  'Content-Type': 'application/json'
}
var data = JSON.stringify({
  uid: params.uid,
  Type: params.type
});
return this.http.post('https://' +
params.apiBaseUrl + '/Tracker/api/Track/Consented/', data, { 'headers': requestHeaders });

}

So everything works perfectly fine.

However, I do need to get a new token every time before calling Tracker(). How can I call GetNewToken() and wait for it to finish and then do Tracker() with the new token? Every time I do this, I get an error .map() does not support void - which I understand is because I'm first trying to get the token and then return the value from Tracker() which obviously isn't the right way - but I don't know with my limited knowledge how to first get the token when the Observable Tracker() is calling that function...

Would really appreciate any help.

1 answer

  • answered 2021-05-15 14:53 Felix

    It doesn't look like RxJS 7 to me since you're not using pipe to chain operators. Anyway, to map observables you need to use switchMap, like this:

    getTracker(params): Observable<any> {
      return getNewToken().pipe(switchMap(token => {
        // fill headers and data
        return this.http.post(url, data, { 'headers': requestHeaders });
      }));
    }
    

    Or without pipe, in case you're using an older version of RxJS:

    getTracker(params): Observable<any> {
      return getNewToken().switchMap(token => {
        // fill headers and data
        return this.http.post(url, data, { 'headers': requestHeaders });
      });
    }