2017-04-09 114 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