【问题标题】:Observable not refreshing the view - Angular 2+Observable 不刷新视图 - Angular 2+
【发布时间】: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(); 吗?

标签: angular rxjs


【解决方案1】:

或许你可以试试 NgZone

ts

isAuth = false;

constructor(private _auth:AuthService, private ngZone: NgZone) {
ngZone.run(() => {
   _auth.authState.subscribe(state => this.isAuth = state)
  });
}

【讨论】:

  • 您好,我刚刚尝试了 NgZone,但仍然无法正常工作。我编辑了我的帖子并添加了 login.ts。我正在使用 Firebase 进行 Facebook 登录。
  • login.ts 什么时候执行?是在第二个代码 sn-p 的构造函数之前还是之后?
  • 首先调用login.ts。它解决了 facebook 登录承诺并调用 authService 并更改回家的路线。
  • 当您登录_auth.authState.subscribe(state =&gt; this.isAuth = state) 这一行时,isAuth 是否符合您的预期?
  • 是的,this.isAuth 在记录时从 false 更改为 true,但视图没有更改。另一方面,当我执行登录流程但没有调用 firebase facebook 登录时,一切都按预期工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 2023-03-28
相关资源
最近更新 更多