2017-09-15 59 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

很高兴听到它:) –