我有以下功能是服务提供者。我想将后端和 UI 部分分开,因此我使用提供程序来获取所有数据。
getUserById(id: number) {
return new Promise((resolve, reject) => {
this.apollo.query({
query: UserByIdQueryText,
variables: {
id: id
}
}).subscribe((res: any) => {
let ans = res.data.user;
if (ans) {
console.log(ans);
resolve(ans);
} else {
reject('could not get user');
}
}, (err) => {
console.error(err);
});
});
}
在实际页面中,我有以下代码来获取数据。
export class UserProfilePage {
public user: User;
public id: number;
constructor(private userService: UserService, private navController: NavController, private params: NavParams) {
this.user = null;
this.id = params.get("id");
this.userService.getUserById(this.id)
.then((user: User) => {
this.user = user;
});
}
}
问题是远程调用完成较晚,但视图试图显示数据。我收到以下错误。
Error: Uncaught (in promise): TypeError: Cannot read property 'title' of null
TypeError: Cannot read property 'title' of null
at Object.eval [as updateRenderer] (ng:///AppModule/UserProfilePage.ngfactory.js:273:28)
at Object.debugUpdateRenderer [as updateRenderer] (http://localhost:8100/build/main.js:12978:21)
at checkAndUpdateView (http://localhost:8100/build/main.js:12357:14)
at callViewAction (http://localhost:8100/build/main.js:12667:17)
at execComponentViewsAction (http://localhost:8100/build/main.js:12613:13)