Angular 2如何制作嵌套的observable

时间:2016-10-27 00:08:47

标签: http angular angular2-observables

我正在尝试编写我们的httpService,它应该有一个post方法,检查一个cookie是否存在带有auth令牌,如果确实存在,那么它应该附加auth头并发出post请求。

但是如果cookie不存在,我需要加载一个包含令牌的本地json文件,并用它来创建cookie,然后附加auth头并发出帖子请求。

我遇到的问题是,如果cookie不存在,我需要观察另一个可观察的观察者。我曾经认为解决方案是使用switchMap,但这并不适合.subscribe,这是http.post请求初始化所必需的。

  private makePostRequest(address: string, payload: any, callback: any): Observable<any> {
    return this.http.post(address, payload, { headers: this.headers })
      .map(callback)
      .catch(( error: any ) => this.handleError(error));
  }

  public post(address: string, payload: any, callback: any): Observable<any>     {
       if (this.hasOAuth2()) {
         this.appendHeader(this.cookieService.get('oauth2'));
         return this.makePostRequest(address, payload, callback);
       } else if (this.isLocalhost()) {
         return this.setAuthCookie()
           .switchMap(() => this.makePostRequest(address, payload, callback));
       } else {
         return this.handleError('Could not locate oauth2 cookie');
       }
  }

  private setAuthCookie(): Observable<any> {
    return this.http.get('./json/token.json')
      .map((res: Response) => {
        let oauth2: any = res.json();
        this.cookieService.set('oauth2', oauth2.access_token, oauth2.expiration);
        this.appendHeader(oauth2.access_token);
      })
      .catch((error: any) => {
        console.log('No dev token was found', error);
        return Observable.throw(error);
      });
  }

更新:奇怪的是,确切的游戏代码或多或少地与get请求一起正常工作。

  private makeGetRequest(address: string, callback: any): Observable<any> {
    return this.http.get(address, { headers: this.headers })
      .map(callback)
      .catch(( error: any ) => this.handleError(error));
  }

  public get(address: string, callback: any): Observable<any> {
      if (this.hasOAuth2()) {
        this.appendHeader(this.cookieService.get('oauth2'));
        return this.makeGetRequest(address, callback);
      } else if (this.isLocalhost()) {
        return this.setAuthCookie()
          .switchMap(() => this.makeGetRequest(address, callback));
      } else {
        return this.handleError('Could not locate oauth2 cookie');
      }
  }

解决方案:我没有订阅httpService.post observable,因此它没有被初始化。

2 个答案:

答案 0 :(得分:0)

在第二种情况下添加空.subscribe()

return this.setAuthCookie()
          .map(() => { })
          .switchMap(() => { // I need to switchMap due to the http.get request in the setAuthCookie method
            this.makePostRequest(address, payload, callback).subscribe(); // Again I need this or the post request won't be made
          }).subscribe(); // <--- here

它将激活http呼叫。

答案 1 :(得分:0)

我从未订阅过我的httpService.post observable,因此它从未被初始化。添加后来的订阅调用导致它被错误地初始化。