阿波罗Angular2客户端处理承诺



>我有以下函数是服务提供商。我想将后端和 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});
}

最新更新