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



我有一个全局服务userAuthService,只要auth令牌在我的应用程序中有效,就会启动它,然后在Profile组件中订阅该服务以加载登录的用户数据。我可以看到数据加载在控制台日志中,但数据不会显示在html中,直到我离开Profile组件并返回,然后显示数据。简而言之,如果我从其他路由路由到Profile组件,则会显示数据,否则,如果Profile组件是我的应用程序加载的第一个页面,则永远不会显示数据。

用户身份验证服务:

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

app.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.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>

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

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

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

请告诉我它是否能阻止

最新更新