在http之前等待令牌检索

时间:2018-02-11 23:14:32

标签: angular

我正在尝试创建一个用于获取数据的服务,该服务将首先确保存在有效的令牌。

我的代码是:

的AccountService:

export class AccountService {

    private tokenUrl = 'api/account/authorize';  
    private _token: Token;

    constructor(
        private http: HttpClient) { }

    /** GET token information from the server */
    getToken(refresh: boolean): Observable<Token> {
        if (!!this._token && !refresh) {
            console.log('returning cached token', this._token);
            return of(this._token);
        }
        return new Observable(observer =>{
            this.http.post<Token>(this.tokenUrl, {})
            .pipe(
                tap(token => this._token = token),
                tap(token => observer.next(token)),
                catchError(this.handleError('getToken', null))
            );
        })
    }
}

我也在尝试缓存收到的令牌,所以每次请求令牌时都不需要发帖子,除非明确请求令牌。

InfoService中:

@Injectable()
export class InfoService {

    private infoBaseUrl = 'api/info/';  // URL to web api
    private _selectionOptions: SelectionOptionsResult;

    constructor(
        private http: HttpClient,
        private accountService: AccountService) { }

    getfilterOptions(filters: SelectionOptionRequest): Observable<SelectionOptionsResult> {

        var tokenObservable = this.accountService.getToken(false);

        console.log('THIS SUCCESFULLY HITS');

        return tokenObservable.switchMap((token) => {

            console.log('THIS NEVER HITS');

            let httpParams = new HttpParams();
            Object.keys(filters).forEach(function (key) {
                httpParams = httpParams.append(key, filters[key]);
            });
            var httpOptions = {
                headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                    authorization: 'Bearer ' + token.access_Token
                }),
                params: httpParams
            };  

            return this.http.get<SelectionOptionsResult>(this.infoBaseUrl + 'GetfilterOptions', httpOptions)
                .pipe(
                    tap(so => this._selectionOptions = so),
                    catchError(this.handleError('getfilterOptions', null))
                );

        })
    }
}

组件

getfilterOptions(filters: SelectionOptionRequest): void {
    this.infoService.getfilterOptions(filters)
        .subscribe(so => this.filterOptions = so);
}

虽然它确实进入getFilterOptions,但它永远不会到达getToken。我错过了什么?

2 个答案:

答案 0 :(得分:0)

Angular使用&#34;冷&#34;观察者(https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339)。因此,在您订阅它之前,它永远不会被执行。我相信如果您将代码略微更改为

var tokenObservable = this.accountService.getToken(false).subscribe(() => {});

一切都将按预期开始工作。我很满意99%,所以请告诉我它是否会修复你的代码。

答案 1 :(得分:0)

抱歉:: glups :: 为什么不? (我不知道observer.next(令牌)的功能)

return this.http.post<Token>(this.tokenUrl, {})
            .pipe(
                tap(token => this._token = token),
                catchError(this.handleError('getToken', null))
            );
        })