我的服务器给了我这样的json。
[
{
"userId": 11,
"positionId": 2,
"emailAddress": "ada.lovelace@gmail.com",
"username": "adalovelace",
"createdBy": 1,
"createdAt": "2018-01-06 13:43:18",
"updatedBy": null,
"updatedAt": "2018-01-06 13:43:18",
"profile": {
"userProfileId": 1,
"userId": 11,
"displayName": "adalovelace",
"location": null,
"title": null,
"imageUrl": null,
"about": null,
"threadCount": 0,
"threadPostCount": 1,
"threadKarma": 0,
"threadPostKarma": 2
}
}
]
我的.ts文件看起来像这样,我删除了很多不相关的代码。
import { UserService } from '../_shared/services/user.service';
import { UserInterface } from '../_shared/interfaces/user.interface';
export class ProfileComponent implements OnInit, OnDestroy {
private currentUser = <UserInterface>{};
public username: string;
public userProfile = <UserInterface>{};
ngOnInit() {
this.userSubcription = this.userService.showProfile(this.username)
.subscribe((userProfile: UserInterface) => {
this.userProfile = userProfile;
console.log(this.userProfile); // has value!
}, error => {
console.log(error);
});
}
}
.html文件
<section id="profile">
<div class="container">
<div class="row">
<div class="col">
<h2>{{userProfile.userId}}</h2>
<h2>{{userProfile.profile.dsplayName}}</h2>
</div>
</div>
</div>
它没有给我任何东西。 userProfile.profile.dsplayName甚至给我错误。它说未定义。
用户界面如下所示。
import { UserProfileInterface } from './user-profile.interface';
export interface UserInterface {
userId: number;
token: string;
username: string;
emailAddress: string;
createdBy: string;
createdAt: string;
updatedBy: string;
updatedAt: string;
positionId: number;
password: string;
confirmPassword: string;
profile: UserProfileInterface;
}
是因为我使用界面吗?我有另一个类似的页面,它使用接口与接口数组,但它的工作原理。
答案 0 :(得分:1)
您的服务器返回json数组。请尝试以下代码段
<section id="profile">
<div class="container">
<div class="row">
<div class="col">
<h2>{{userProfile[0].userId}}</h2>
<h2>{{userProfile[0].profile.dsplayName}}</h2>
</div>
</div>
</div>