【发布时间】:2020-02-22 23:29:42
【问题描述】:
我有一个 API,它返回 Profile 信息,我正在我的 HTTP 服务中获取它。嵌套对象User 有一个方法getRole()。但是当我试图调用这个方法时,我得到了
ERROR TypeError: _co.profile.user.getRole 不是函数
当我从我的其他服务获取User 时,它只返回User 实体,我可以毫无问题地调用此函数。
我错过了什么?
型号
export class Profile {
user: User;
apiKeys: ApiKey[];
}
export class User {
user: string;
firstname: string;
surname: string;
email: string;
role: Role;
active: boolean;
getRole() {
switch (this.role) {
case Role.READ: {
return "READ";
}
case Role.WRITE: {
return "WRITE";
}
case Role.ADMIN: {
return "ADMIN";
}
default : {
return "READ";
}
}
}
}
ProfileService.ts
getProfile(): Observable<Profile> {
return this.http.get<Profile>(this.profileUrl).pipe(catchError(this.handleError));
}
Component.ts
profile: Profile;
isProfileAvailable:boolean = false;
ngOnInit() {
this.settingsService.getProfile().subscribe(profile => {
this.profile = profile;
this.isProfileAvailable = true;
});
}
Component.html
<p-fieldset [legend]="Profile" *ngIf="isProfileAvailable">
<div><b>User: </b>{{profile.user.firstname}}</div>
<div><b>E-mail: </b>{{profile.user.email}}</div>
<div><b>Role: </b>{{profile.user.getRole()}}</div>
</p-fieldset>
【问题讨论】:
-
请对我们的回答提供一些反馈。谢谢!
-
@Blauharley 这些天我一直很忙,但我会尽快尝试您的解决方案并给您反馈。
-
请提供一些反馈。
-
@Blauharley 抱歉让我等了这么久,我终于有时间看看你的解决方案了。非常感谢,成功了!
-
不客气。谢谢!
标签: angular angular-http ngoninit