2017-09-15 7 views
1

ネストされたオブザーバブルの2つが完了してから別のページにナビゲートするまで待つ必要があります。 これはネストされているため、これを行う最善の方法は何か分かりません。そのため、Angularアプリに同期の問題があります。 Observablesが私の認証サービスで設定されています。 authentication.service.ts:角2はネストされたオブザーバブルが終了するまで待ちます

login(username: string, password: string) { 
     let reqUrl = AppSettings.__USER_TOKEN_URL; 
     let reqHeaders = this.authConfig.token.headers; 
     let reqBody = encodeURI(
      this.authConfig.token.body 
       .replace(/{{ username }}/g, username) 
       .replace(/{{ password }}/g, password)); 

     // 
     // Get token, then get user identity, if login successfull. 
     // 

     return this.http.post(reqUrl, reqBody, reqHeaders) 
      .map((response) => this.getIdentity(response)) 
      .catch(this.handleErr); 
    } 

private getIdentity(response: Response) { 

     // 
     // Get user identity based on token. 
     // 

     let body = response.json(); 
     let token = body.access_token; 

     if (null != token && undefined != token) { 
      this.authConfig 
       .identity 
       .headers 
       .headers.set('authorization', 'Bearer ' + token); 

      let reqUrl = AppSettings.__USER_IDENTITY_URL 
      let reqHeaders = this.authConfig.identity.headers; 
      let reqbody = this.authConfig.identity.body; 

      return this.http.post(reqUrl, reqbody, reqHeaders) 
       .map((response) => this.setUser(response)) 
       .catch(this.handleErr) 
       .subscribe(); 
     } 
    } 

はその後、私のログイン・コンポーネントで、私はサービスログイン()メソッドを呼び出すようにしようとしている、それが終了すると、私は別のインスタンスに移動したいです。 login.component.ts

login() { 
     this.loading = true; 
     this.authenticationService.login(this.model.username, this.model.password).subscribe(
      data => { }, 
      error => { console.log('Error authenticating: ' + error); }, 
      () => { this.router.navigate([this.returnUrl]) }); 
    } 

しかし、それは働いていません。 Observablesはrouter.navigateがトリガされても実行されています。 Angular新人のアイデアはありますか? ありがとうございます。

答えて

0

subscribegetIdentity()と呼びますが、2つの観測値をの順番に並べることは問題です。です。

代わりに、サブスクリプションオブジェクトではなく、オブザーバブルオブジェクトを返す必要があります。switchMapを使用してください。

getIdentity:ログインコールで

private getIdentity(response: Response) { 

     // 
     // Get user identity based on token. 
     // 

     let body = response.json(); 
     let token = body.access_token; 

     if (null != token && undefined != token) { 
      this.authConfig 
       .identity 
       .headers 
       .headers.set('authorization', 'Bearer ' + token); 

      let reqUrl = AppSettings.__USER_IDENTITY_URL 
      let reqHeaders = this.authConfig.identity.headers; 
      let reqbody = this.authConfig.identity.body; 

      return this.http.post(reqUrl, reqbody, reqHeaders) 
       .map((response) => this.setUser(response))//return observable. 
     } 
} 

return this.http.post(reqUrl, reqBody, reqHeaders) 
     .switchMap((response) => this.getIdentity(response)) 
     .catch(this.handleErr); 

switchMap第二観察に切り替えて最初の完了時に、それを返します。

+0

イデア 'switchMap'も存在していなかった。それは今働いている。どうもありがとうございました。 –

+0

聞いてうれしいです:) –

関連する問題