Profile
情報を返すAPIがあり、HTTPサービスで取得しています。ネストされたオブジェクトUser
にはメソッドがありgetRole()
ます。しかし、このメソッドを呼び出そうとすると、
エラー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>
呼び出しhttp.get<Profile>
は型のオブジェクトを自動的に初期化しないProfile
ため、プロパティuser
も型のオブジェクトでUser
はなく、メソッドを取得していませんgetRole
。
Object.assignを使用して、オブジェクトとそのプロパティを初期化できます。また、2つのクラスタイプ(Profile
、User
)があるため、両方をBase
-Classから拡張して、両方のタイプのプロパティの割り当てを処理できます。
モデル:
// Use a Base class to assign all properties with objects both of type Profile and User
class Base {
constructor(properties?: any) {
(Object as any).assign(this, properties);
}
}
export class User extends Base {
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";
}
}
}
}
export class Profile extends Base {
user: User;
apiKeys: ApiKey[];
// take advantage of Object.assign
// to initialize an instance of type Profile
// along with it's property user
constructor(properties?: any) {
super(properties);
this.user = new User(properties.user);
}
}
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(profileData => {
// assuming that profileData looks like this:
/*
{
user: {
user: 'user',
firstname: 'firstname',
surname: 'surname',
email: 'email',
active: true
}
}
*/
this.profile = new Profile(profileData);
this.isProfileAvailable = true;
});
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加