【发布时间】:2025-12-03 08:05:02
【问题描述】:
在尝试解决 Google 身份验证的执行顺序问题(即等待异步调用完成)时,我遇到了这个奇怪的错误。如果我不添加.subscribe,一切正常,但我试图等到谷歌弹出窗口返回后再继续其他事情。我正在尝试更改“signIn()”以返回一个 observable(它曾经不返回任何内容),我遇到了这个错误:
TypeError:无法读取未定义的属性“订阅”。
订阅发生错误的部分:
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;
});
}
}
仅供参考:我之前的问题导致了这种变化:Angular - waiting for Google authentication to complete
【问题讨论】:
标签: angular google-authentication angular2-observables