代码之家  ›  专栏  ›  技术社区  ›  Hoàng Nguyễn

角度6-数据加载在控制台日志中,但不显示在html中

  •  0
  • Hoàng Nguyễn  · 技术社区  · 6 年前

    我有全球服务 userAuthService

    用户身份验证服务:

      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());
      }
    

      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.ts文件:

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

    profile.component.html文件:

    <div>{{identity?.email}}</div>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Evgeniy Boytsov    6 年前

    你可以创造 identity$ 主题- public identity$ = this.userAuthService.identity$ ;

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

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