如何从retryWhen angular2调用父函数

时间:2016-11-01 22:25:48

标签: angular typescript rxjs

我正在尝试从retryWhen执行一个函数,并在retryWhen完成后调用父函数。我怎么能这样做?

getStatuses(statusesType: string[]): Observable<IStatus[]> {

        let body = JSON.stringify({ "StatusesType": statusesType});
        let headers = new Headers({ 'Content-Type': 'application/json' });
        headers.append('Authorization', 'Bearer ' + localStorage.getItem("access_token");
        headers.append('Access-Control-Allow-Origin', '*');
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this._baseUrl + '/statuses/statusesList', body, options)
            .retryWhen(error => this.refreshToken())
            .map((res: Response) => {
                this.statusesrecieved = res.json();
                return this.inspections;
            });
    }

我想在retryWhen中执行refreshToken()后再次调用getStatuses()函数。感谢帮助

我也尝试过像这样的重试,这也没有用。

 return this.http.post(this._baseUrl + '/statuses/statusesList', body, options)
                .retryWhen(error => this.refreshToken())
                .map((res: Response) => {
                    this.statusesrecieved = res.json();
                    return this.inspections;
                }).retry(5);
        }

这是我的refreshToken函数

refreshToken(): Observable<any> {
        console.log("refreshing token");

        let body: string = 'grant_type=refresh_token&refresh_token=' + localStorage.getItem("refresh_token");
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        let options = new RequestOptions({ headers: headers });


        return Observable.create(
            (observer: Observer<any>) => {
                this.http.post('https://fedqa.test.com/as/token.oauth2', body, options)
                    .map(res => res.json()).subscribe(
                    (data) => {

                        localStorage.removeItem("access_token");
                        localStorage.removeItem("refresh_token");
                        localStorage.setItem("access_token", data.access_token);
                        localStorage.setItem("refresh_token", data.refresh_token);
                        localStorage.setItem("token_type", data.token_type);
                        localStorage.setItem("expires_in", data.expires_in);
                    },
                    (error) => {

                        Observable.throw(error);
                    }
                    );
            });
    }

1 个答案:

答案 0 :(得分:0)

我假设:

  1. 假设this.refreshToken() async并返回一个完成后完成的Observable。
  2. this.refreshToken()更新为副作用,并且一旦Observable完成就会更新。
  3. 您可以使用concat获取在前一个完成后订阅的可观察量(!!)。

    getStatuses()会立即在本地存储中查找令牌,因此无法在concat中直接使用,必须在this.refreshToken完成后触发,Observable.defer来到记:

    ...
    .retryWhen(
      errors => this.refreshToken()
        .concat(Observable.defer(() => getStatuses(statusesType)))
    )
    

    虽然这对你有用,但我发现潜在的无限递归。您可能还想查看retry,其中包含在发出错误之前要执行的最大重试次数。