【发布时间】:2017-10-29 14:28:55
【问题描述】:
我遇到了同样的问题。我尝试在导航栏组件中显示用户的性别。我要求我的服务为我获取用户对象,然后我尝试设置我的“性别”以在 HTML 中使用。问题是我需要刷新页面才能显示性别。有什么帮助吗? :)
export class NavbarComponent implements OnInit {
title = 'navbar';
userIsLoggedIn: boolean;
user: User;
currentUser: Parent;
gender: string;
constructor(private authenticationService: AuthenticationService, private router: Router, private parentService: ParentService) {
authenticationService.userIsloggedIn.subscribe(isLoggedIn => {
this.userIsLoggedIn = isLoggedIn;
this.user = authenticationService.getUser();
});
}
ngOnInit(): void {
this.user = this.authenticationService.getUser();
this.userIsLoggedIn = this.user != undefined;
this.getParentFromUserEmail(this.user.email);
this.getSex();
}
private getParentFromUserEmail(email: string) {
this.parentService.getByEmail(email).map(
(response) => this.currentUser = response).subscribe(data => {
this.gender = data.type;
});
}
getSex() {
return this.gender;
}
}
HTML 代码
<div class="sidebar-account-content">
<h3>{{user?.firstname}} {{user?.lastname}}</h3>
<p *ngIf="getSex()">Test</p>
<p *ngIf="gender === 'F'">Father</p>
<p *ngIf="gender === 'M'">Mother</p>
</div>
【问题讨论】:
-
第一次加载页面时,您是否在控制台中遇到任何错误?在 Plunker 中设置代码以重现您可能遇到的问题?
-
你在哪里显示性别,我只看到硬编码文本“父亲”、“母亲”、“测试”