2017-09-05 107 views
1

尝试解决Google身份验证的执行顺序问题(即等待异步调用完成)时,我遇到了这个奇怪的错误。如果我不添加.subscribe,但一切正常,但我试图等到Google弹出窗口返回后再继续处理其他事情。我试图改变“签到()”返回一个可观察到的(它使用的不返回任何东西),我碰到这个错误:Angular - TypeError:无法读取undefined的属性'subscribe'

TypeError: Cannot read property 'subscribe' of undefined.

订阅部分,其中发生错误:

this._authService.signIn().subscribe(
     value => console.log(value), 
     error => console.error(error), 
    () => console.log("done") 
    ); 

和更改服务方法:

signIn(): Observable<boolean> { 
    const signOptions: gapi.auth2.SigninOptions = {scope: SCOPES }; 
    if (this._googleAuth) 
     Observable.fromPromise(this._googleAuth.signIn(signOptions))  
     .subscribe(response => { 
     var user:any = response; 
     if(response === true) { 
      this.handleSuccessLogin(user); 
      return Observable.of(true); 
     } 
     else { 
      return Observable.of(false); 
     } 
     }); 
    } 
    else { 
     console.error("Google Authentication not initialized"); 
     return Observable.of(false); 
    } 
    } 

更新:这是我的版本直接从签到返回。按照第一个建议:

signIn(): Observable<{}> { 
    const signOptions: gapi.auth2.SigninOptions = {scope: SCOPES }; 
    if (this._googleAuth) { 
     return Observable.fromPromise(this._googleAuth.signIn(signOptions))  
     .map(response => { 
     var user:any = response; 
     if(response === true) { 
      this.handleSuccessLogin(user); 
     } 
     return response; 
     }); 
    } 
    } 

FYI:我刚才的问题,导致这一变化:Angular - waiting for Google authentication to complete

回答

1

从异步调用返回的结果将无法正常工作。您可以更改this._googleAuth分支直接在map部分返回可观察到的,做你想要的东西:

return Observable.fromPromise(this._googleAuth.signIn(signOptions))  
     .map(response => { 
      var user:any = response; 
      if(user) { 
      this.handleSuccessLogin(user); 
      return true; 
      } else { 
      return false; 
      } 
     }); 

参考Plunker demo

+0

谢谢,我很欣赏这个例子。我正在尝试你的建议,但它并没有返回任何东西,并且handleSuccessLogin()调用也没有触发。查看我的更新。我搞砸了什么? – beachCode

+0

@beachCode你应该仍然保持你的其他分支 – Pengyy

+0

@ beachCode更改'signIn():Observable <{}>'到'signIn():Observable '并确保您的'this._googleAuth.signIn(signOptions)'可以得到回应。 – Pengyy

相关问题