2017-04-09 111 views
0

我有以下功能是服务提供者。我想分开保留后端和UI部分,因此我使用提供程序来提取所有数据。Apollo Angular2客户端处理承诺

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) 

回答

0

关于你的代码。你能提供一些关于你连接的数据库的细节吗? 我假设你正在使用的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}); 
} 
+0

我正在使用与GraphQL后端数据相关的Apollo客户端。我想用Apollo来获取数据... – Purus