【问题标题】:Angular 5 HTTP Observable GET Request handle nested objectsAngular 5 HTTP Observable GET 请求处理嵌套对象
【发布时间】: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


【解决方案1】:

如果您只想从服务中返回data 属性的内容,您可以使用map

getPosts(): Observable<Post[]> {
    this.http.get(this.postsurl)
            .map(resp => resp.json())
            .map(body => body.data);
}

如果您需要对元素进行处理以将它们转换为您的特定对象类型,那么您也可以在 map 函数中执行此操作。

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 2016-04-22
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2015-03-19
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多