2017-09-15 54 views
1

我需要等到我的兩個嵌套Observable才能在導航到另一個頁面之前完成。 我不知道什麼是嵌套的最佳方式,因此我在Angular應用程序中遇到同步問題。 觀察對象正在我的驗證服務中設置。 authentication.service.ts:Angular 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]) }); 
    } 

但它不工作。當router.navigate被觸發時,觀察對象仍在運行。 Angular菜鳥的任何想法? 在此先感謝。

回答

0

問題是你只是簡單地撥打subscribe裏面getIdentity()這不會使兩個可觀察到的順序

取而代之,您需要返回可觀察的而不是訂閱對象,並使用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

甚至沒有ideia'switchMap'存在。它正在工作。非常感謝你。 –

+0

很高興聽到它:) –