简体   繁体   English

返回可观察位首先在 Angular 11 / RxJS 7 中获取新令牌

[英]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! Angular / RxJS 试图在疯狂的压力下学习它,我真的很艰难!

If I'm returning this Observable:如果我要返回这个 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 function 只是一个简单的 http.post 返回,像这样:

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().但是,每次调用 Tracker() 之前,我都需要获取一个新令牌。 How can I call GetNewToken() and wait for it to finish and then do Tracker() with the new token?如何调用 GetNewToken() 并等待它完成,然后使用新令牌执行 Tracker()? 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...每次我这样做时,我都会得到一个 error.map() does not support void - 我理解这是因为我首先尝试获取令牌,然后从 Tracker() 返回值,这显然不是正确的方法- 但我不知道如何在 Observable Tracker() 调用 function 时首先获取令牌...

Would really appreciate any help.非常感谢任何帮助。

It doesn't look like RxJS 7 to me since you're not using pipe to chain operators.对我来说,它看起来不像 RxJS 7 ,因为您没有使用pipe来链接运营商。 Anyway, to map observables you need to use switchMap , like this:无论如何,对于 map 可观察对象,您需要使用switchMap ,如下所示:

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:或者没有 pipe,如果您使用的是旧版本的 RxJS:

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

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

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