2017-09-05 108 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

相關問題