Angular - TypeError: Cannot read property 'subscribe' of undefined

Angular - TypeError: Cannot read property 'subscribe' of undefined

在尝试通过 Google 身份验证解决执行顺序问题时(即等待异步调用完成),我 运行 遇到了这个奇怪的错误。如果我不添加 .subscribe,一切正常,但我试图等到 Google 弹出窗口 window 已 returned,然后再继续其他事情。我正在尝试将 "signIn()" 更改为 return 一个可观察对象(它以前不是 return 任何东西),我 运行 遇到了这个错误:

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);
    }
  }

更新:这是我直接从登录中 returning 的版本。根据第一个建议:

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;
      });
    }
  }

仅供参考:导致此更改的我之前的问题:Angular - waiting for Google authentication to complete

异步调用的返回结果不会按预期工作。您可以直接将 this._googleAuth 分支更改为 return 一个 Observable 并在 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.