Angular 6-数据已加载到控制台日志中但未显示在html中

时间:2018-11-08 09:28:56

标签: angular

我有一个全局服务> s <- x+y > s [1] 3 33 34 49 > z+s [1] 6 37 88 55 ,只要身份验证令牌在我的应用程序中有效,它就会启动,然后在“个人档案”组件中订阅该服务以加载已登录的用户数据。我可以看到数据已加载到控制台日志中,但是直到我离开Profile组件并返回时,数据才显示在html中,然后显示了数据。简而言之,如果我从其他路线路由到Profile组件,则显示数据,否则,如果Profile组件是我的应用加载的第一页,则数据将永远不会显示。

用户身份验证服务:

userAuthService

app.component.ts:

  private identity = new BehaviorSubject(<Identity>{});
  public identity$ = this.identity.asObservable();

  private isValidToken = new BehaviorSubject<boolean>(false);
  public isValidToken$ = this.isValidToken.asObservable();

  constructor(
    private store: Store<AppState>,
    private router: Router,
    private apiService: ApiService,
  ) {
    this.store.select('tokens').subscribe((tokens: AuthToken) => {
      this.tokens = tokens;
      if (tokens && this.hasValidToken()) {
        this.isValidToken.next(true);
      } else {
        this.isValidToken.next(false);
      }
    });

    this.store.select('identity').subscribe((identity: any) => {
      if (identity.identity) {
        this.setIdentity(identity.identity);
      } 
    });
  }  

  setIdentity(identity: Identity) {
    this.identity.next(identity);
  }

  getIdentity() {
   this.store.dispatch(new identityActions.GetIdentityAction());
  }

profile.component.ts:

  constructor(
    private store: Store<AppState>,
    private userAuthService: UserAuthService,
  ) {
    this.storeSub = this.store.select('tokens').subscribe((tokens: AuthToken) => {
      this.validToken = this.userAuthService.hasValidToken();
    });

    this.tokenSub = this.userAuthService.isValidToken$.subscribe((bool: boolean) => {
      this.validToken = bool;
      if (bool) {
        this.userAuthService.getIdentity();
      }
    });
  }

profile.component.html:

  constructor(
    private userAuthService: UserAuthService
  ) {
    this.idenSub = this.userAuthService.identity$.subscribe((res: Identity) => {
      this.identity = res;
      console.log(this.identity);
    });
  }

1 个答案:

答案 0 :(得分:0)

您可以创建identity$个主题- public identity$ = this.userAuthService.identity$;

并使用管道异步订阅模板:

<div *ngIf="identity$ | async as identity">
   {{identity.email}}
</div>

请告诉我它是否变平