添加本地存储变量后,Angular2视图未更新

时间:2017-06-11 10:02:28

标签: javascript angular

我有一个登录组件,当用户登录时,当前用户详细信息存储在本地存储变量中。因此,当登录成功时将当前用户详细信息存储在本地存储变量中并导航到仪表板,我已使用本地存储变量获取用户详细信息并显示在网页页眉中,但刷新页面后视图不会更改我会.. ..

  login() {
    this.authenticationService.login(this.model.username, 
     this.model.password)
        .subscribe(
            data => {
                this.activeModal.dismiss();
                this.router.navigate(['dashboard']);
            },
            error => {
                this.alertService.error(error);
            });
 }

在服务中

  login(username: string, password: string) {
    return this.http.post('/api/authenticate', JSON.stringify({ username: 
     username, password: password }))
        .map((response: Response) => {
            // login successful if there's a jwt token in the response
            let user = response.json();
            if (user && user.token) {
                // store user details and jwt token in local storage to keep 
               user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
            }
        });
   }     

   getCurrentUser() {
    return JSON.parse(localStorage.getItem('currentUser'));
   }

导航组件

  constructor(private authenticationService: AuthenticationService) {
    getUser() {
      this.currentUser = this.authenticationService.getCurrentUser();
    }
  }

查看

  <li *ngIf="currentUser"><a href="#">Welcome {{currentUser.firstName}}</a>
  </li>
  <li *ngIf="currentUser"><a href="#" (click)="logout()">Logout</a></li>
  <li *ngIf="!currentUser"><a href="#" (click)="openLoginModal()">Login</a>
  </li>
  <li *ngIf="!currentUser"><a href="#" (click)="openRegisterModal()">Register</a></li>

我找到的解决方案是使用DoCheck生命周期钩子。 除了默认算法

之外,还会调用ngDoCheck来检查指令中的更改
 ngDoCheck() {
    this.getUser();
 }

0 个答案:

没有答案