【问题标题】:Apollo Angular2 client handling promiseApollo Angular2 客户端处理承诺
【发布时间】:2017-09-04 07:55:58
【问题描述】:

我有以下功能是服务提供者。我想将后端和 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)

【问题讨论】:

    标签: angular apollo apollo-client


    【解决方案1】:

    关于您的代码。您能否提供有关您正在连接的数据库的一些详细信息? 我假设您使用 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});
    }
    

    【讨论】:

    • 我正在使用与 GraphQL 后端数据相关的 Apollo 客户端。我想使用 Apollo 来获取数据...
    猜你喜欢
    • 2021-10-12
    • 2019-06-09
    • 2017-09-14
    • 2022-11-13
    • 2022-12-29
    • 2020-12-27
    • 2017-12-08
    • 2019-04-03
    • 2021-08-13
    相关资源
    最近更新 更多