登录后未重新加载Angular组件

时间:2019-06-28 03:55:45

标签: angular

我有一个登录的Auth服务,但是它不能实时更新该组件。 Angular不这样做吗?

登录组件ts,不在ngOnInit中:

onSubmit() {
    this.authService.login(this.f.username.value, this.f.password.value)
    .pipe(first())
    .subscribe(
    data => {
         this.router.navigate([this.returnUrl]);
    },
    error => {
        this.error = error;
        this.loading = false;
    });
}

在用户组件HTML文件中,

<ul class="logged-in" *ngIf="currentUser">
  <li>Logged in menu item</li>
</ul>

用户组件ts:

export class UserMenuComponent implements OnInit {
  currentUser: User;
  userFromApi: User;

  constructor(
      private userService: UserService,
      private authService: AuthService
  ) {
     this.currentUser = this.authService.currentUserValue;
  }

  UserMenu(){
    if(this.currentUser){
      this.userService.getById(this.currentUser.id).pipe(first()).subscribe(user => {
        this.userFromApi = user[0];
      });
    }
  }

  ngOnInit() {

    // check user
    this.UserMenu();
  }
}

我正在导入所有相关内容,因此我遗漏了一些显而易见的代码。

如果我刷新它,它将起作用。

1 个答案:

答案 0 :(得分:0)

尝试在Angualar Zone中运行代码。

在您的登录组件中,

onSubmit() {
   this.authService.login(this.f.username.value, this.f.password.value)
   .pipe(first())
   .subscribe(
      data => {
      this.zone.run(() => {
        this.router.navigate([this.returnUrl]);
    });

},
error => {
    this.error = error;
    this.loading = false;
});
}

在构造函数中

constructor(private  zone: NgZone) {}
相关问题