【问题标题】:Variable change is not getting picked up and rerendered in the template with Angular 2+使用 Angular 2+ 在模板中未提取和重新呈现变量更改
【发布时间】:2018-03-28 18:03:39
【问题描述】:

我有一个组件,它作为它的一部分根据配置文件对象呈现用户的名称。

一个模板对应的部分是:

<button mat-button [matMenuTriggerFor]="userMenu" *ngIf="isAuthenticated()">
      {{profile?.name}}
    </button>

并且配置文件正在该组件的 onInit 函数中加载:

ngOnInit() {
    if (this.authService.userProfile) {
      this.profile = this.authService.userProfile;
    } else {
      this.authService.getProfile((err, profile) => {
        this.profile = profile;
      });
    }
  }

当我第一次导航到此页面时,不会呈现名称,即使 isAuthenticated 总是返回 true

如果我刷新页面,它会开始正确呈现。

我做错了什么?

之后,又进行了一些挖掘,似乎它只发生在身份验证之后。

这里是 AuthService 代码:

import { Injectable } from '@angular/core';
import * as auth0 from 'auth0-js';
import { environment } from '../../../environments/environment';
import { Router } from '@angular/router';

@Injectable()
export class AuthService {

  auth0 = new auth0.WebAuth(environment.auth0);

  userProfile: any;

  constructor(private router: Router) {
  }

  public login(): void {
    this.auth0.authorize();
  }

  public handleAuthentication(): void {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        this.setSession(authResult);
        this.router.navigate(['']);
      } else if (err) {
        this.router.navigate(['']);
        console.log(err);
      }
    });
  }

  private setSession(authResult): void {
    // Set the time that the Access Token will expire at
    const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
  }

  public logout(): void {
    // Remove tokens and expiry time from localStorage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    // Go back to the home route
    this.router.navigate(['']);
  }

  public isAuthenticated(): boolean {
    // Check whether the current time is past the
    // Access Token's expiry time
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

  public getProfile(cb): void {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('Access Token must exist to fetch profile');
    }

    const self = this;
    this.auth0.client.userInfo(accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
      }
      cb(err, profile);
    });
  }
}

【问题讨论】:

  • 有变化 changeDetectionStrategy 吗?
  • 请出示您的authService的代码。

标签: angular angular2-template


【解决方案1】:

显然,当用户没有首先登录时,app-nav 在 auth-callback 中首先加载。而且由于每次路由更改时组件都不会重新加载,因此组件没有获取有关登录用户的信息,因此在重新加载之前一直卡在这种情况下。

解决方案是在甚至不应该期望用户存在的路线上甚至不包括导航组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多