【发布时间】:2018-11-27 13:09:56
【问题描述】:
我的 Angular 应用有问题。
我使用 jsonapi.org 的指南创建了一个 api,因此我的 api 看起来像这样:
{
"data": [
{
"type": "posts",
"id": "1",
"attributes": {
"text": "Hello, World!"
},
"relationships": {
"user": {
"data": {
"type": "users",
"id": "1"
},
"links": {
"self": "http://localhost/api/users/1"
}
},
"comments": [
]
},
"links": {
"self": "http://localhost/api/posts/1"
}
}
],
"links": {
"first": "http://localhost/api/posts?page=1",
"last": "http://localhost/api/posts?page=1",
"prev": null,
"next": null,
"self": "http://localhost/api/posts"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://localhost/api/posts",
"per_page": 15,
"to": 1,
"total": 1
},
"included": [
{
"type": "users",
"id": "1"
}
]
}
现在我正在尝试将 api 实现到我的 angular 5 应用程序中。目前我获取这样的数据:
/** GET heroes from the server */
getPosts (): Observable<Post[]> {
return this.http.get<Post[]>(this.postsUrl)
.pipe(
tap(posts => this.log(`fetched posts`)),
catchError(this.handleError('getPosts', []))
);
}
现在的问题是我怎样才能得到正确的对象?因为 Angular 希望对象在 api 的根目录中作为数组,但地雷在“数据”下。
刚刚找到函数“mergeMap”,但它没有按预期工作,所以我仍然遇到同样的问题。
【问题讨论】:
-
console.log(posts)块中的tap给了你什么? -
你可以使用 observables ".map" 函数并返回 posts.data
-
如果你想要result.data,你可以使用map。根据需要映射结果(您的对象具有属性“数据”、“链接”、“元”..):返回 this.http.get
(this.postUrl).pipe(map(result =>{return result.data}) -
哈哈哈是我自己发现的。不过还是谢谢你!它正在工作。
标签: angular laravel rest api angular5