【发布时间】:2019-05-04 07:22:59
【问题描述】:
当我在显示 facebook 弹出窗口后从 login.ts 组件调用 auth.service.ts 中的 login() 或 logout() 时,isAuth 在主页视图中仍然为 false,但如果我在 subscribe() 内执行 console.log(this.isAuth)它在控制台中正确更新。
当我直接拨打login() 或logout() 而不使用firebase facebook 登录时,它工作正常。
首页
HTML
<h1> {{isAuth}} </h1>
TS
isAuth = false;
constructor(private _auth:AuthService) {
_auth.authState.subscribe(state => this.isAuth = state)
}
AuthService
authState = new Subject<boolean>();
login(access_token) {
this.authState.next(true);
}
logout() {
this.authState.next(false);
}
主题是从
导入的从“rxjs/Subject”导入{主题};
login.ts
signInWithFacebook() {
this.afAuth.auth
.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then((res: any) => {
const access_token = res.credential.accessToken;
this._auth.login(access_token);
this._router.navigateByUrl('/home');
});
facebook 承诺已解决,this._auth.login() 被调用,isAuth 已更改但视图未更新...
【问题讨论】:
-
尝试收听 router.events.subscribe(event:Event =>console.log) 以检查 firebase 登录是否进行了会影响您导航到主页的 somd 重定向。并且可能会在 setTimeout 调用中包含一些延迟的导航 - 只是为了检查。
-
您好,路由运行良好。它从登录到主页,但在主页视图中,如果用户登录,this.isAuth 应该从 false 更改为 true。 this.isAuth 仅在控制台中更改。
-
我认为当您路由到它时会重新创建主组件(只需将 console.log 放入 ngOnInit 以确保)。所以之前的真实值(来自subject.next)将会丢失。您最好将其保存在某些服务中,然后使用它的 home 组件。
-
实际上 isAuth 在 header.ts 中不在 home.ts 虽然我刚刚做了 _router.events.subscribe(event =>console.log(event)) 并且它输出了一些关于 '/home ' 和 '/login' 但没有关于不在应用程序路由模块中的“header”组件
-
你可以尝试注入 ChangeDetectorRef,然后将值赋给
isAuth,然后执行this.cdr.markForCheck();吗?