[英]How to create service for angular2 + apollo-client with graphql
[英]Apollo Angular2 client handling promise
我下面的功能是服务提供商。 我想将后端和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)
关于您的代码。 您能否提供有关您正在连接的数据库的一些详细信息? 我假设您将MongoDB用作后端数据存储...如果是这样,这可能会有所帮助:
getUserById(id: number, callback: (error: any, result: any) => void ) {
this.apollo.find({"id":id}, callback);
}
此方法应在DAO对象内的服务器端使用。 然后,您可以使用es6-promise从客户端服务类中获取数据。 如下所示:
getUserById(id: number): Promise<any> {
return this.http.get("someurl/" + id)
.toPromise()
.then((obj) => {
//do your magic
})
.catch(() => {// handle your err});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.