Apollo Angular2客户处理承诺

Apollo Angular2客户处理承诺,angular,apollo,apollo-client,Angular,Apollo,Apollo Client,我有以下功能是一个服务提供商。我希望将后端和UI部分分开,因此我使用提供者获取所有数据 getUserById(id: number) { return new Promise((resolve, reject) => { this.apollo.query({ query: UserByIdQueryText, variables: { id: id } }).subscribe((res: any) => { let ans

我有以下功能是一个服务提供商。我希望将后端和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});
}
getUserById(id:number):承诺{
返回此.http.get(“someurl/”+id)
.toPromise()
.然后((obj)=>{
//施展你的魔法
})
.catch(()=>{//handle your err});
}

我正在使用Apollo客户端,它与GraphQL后端数据相关。我想使用Apollo获取数据。。。