我正在通过可观察的方式跟踪我的应用程序中的用户登录状态。 由于某种原因要注册“退出”事件,我必须单击两次按钮。
经过一些研究,我发现this的答案建议注入changeDetectorRef
。确实可以解决此问题,但是我认为这不是Angular中的错误(如OP所建议的)。我无法在我的toy example中复制此问题。
如果有人能帮助我找出答案,我将不胜感激
chageDetectorRef
changeDetectorRef
解决了这个问题这是我的代码:
login-form.component.html
<div *ngIf="!user" class="card text-center">do stuff </div>
login-form.component.ts
import { GoogleAuthService } from '../shared/google-auth.service';
export class LoginFormComponent implements OnInit {
user: GoogleUser;
constructor(private googleAuth: GoogleAuthService, private changeDetectorRef: ChangeDetectorRef) {
}
ngOnInit() {
this.googleAuth.authState.subscribe((user: GoogleUser) => {
this.user = user;
this.changeDetectorRef.detectChanges(); // this solves the issue
});
}
google-auth.service.ts
export class GoogleAuthService {
clientId = '';
opt: LoginOpt = {scope: 'email'};
protected auth2: any;
protected _readyState: BehaviorSubject<boolean> = new BehaviorSubject(false);
user: GoogleUser;
**I use this to track state**
private _authState: BehaviorSubject<GoogleUser> = new BehaviorSubject(null);
constructor() {
this.initialize().then(() => {
this._readyState.next(true);
this.getLoginStatus().then((user) => {
this.user = user;
this._authState.next(user);
});
}); }
get authState(): Observable<GoogleUser> {
return this._authState.asObservable();
}
signOut(): Promise<any> {
return new Promise((resolve, reject) => {
this.onReady().then(() => {
this.auth2.signOut().then((err: any) => {
if (err) {
reject(err);
} else {
this.user = null;
this._authState.next(null);
resolve();
}
}).catch((err: any) => {
reject(err);
});
});
});
}