【问题标题】:Facing issues on accessing json() in angular, HttpClient. Looking for alternatives面临在 Angular HttpClient 中访问 json() 的问题。寻找替代品
【发布时间】:2020-06-22 22:17:58
【问题描述】:

我想从“https://jsonplaceholder.typicode.com/posts”获取所有帖子。 但是,将 Http 更新为 HttpClient,不允许访问“json()”(在 response.json() 处)。 请指导解决方案。 问候。

export class PostsComponent {
  posts: any[];
  constroctur(http: HttpClient) {
    http
      .get('https://jsonplaceholder.typicode.com/posts')
      .subscribe((response) => {
        this.posts = response.json();
      });
  }
}

【问题讨论】:

  • 你不能访问response里面的数据吗?我不知道返回数据的结构,但类似:response.data 应该包含所有返回的帖子。
  • 看来这里有你的答案stackoverflow.com/questions/52056992/…
  • 使用HttpClient,您无需致电.json()。默认情况下,响应已经是一个json对象

标签: json angular


【解决方案1】:

最好的方法是将数据类型传递给响应参数“response:any[]”。

export class PostsComponent {
  posts: any[];
  constroctur(http: HttpClient) {
    http
      .get('https://jsonplaceholder.typicode.com/posts')
      .subscribe((response : any[]) => {
    this.posts = response;
  });
 }
}

您必须随请求设置内容类型。它应该如下所示。

const headers = { 'Content-Type': 'application/json'};
export class PostsComponent {
posts: any[];
constroctur(http: HttpClient) {
http
  .get('https://jsonplaceholder.typicode.com/posts',{headers})
  .subscribe((response : any[]) => {
    this.posts = response;
  });
 }
}

【讨论】:

    【解决方案2】:
    http
      .get('https://jsonplaceholder.typicode.com/posts')
      .subscribe((response) => {
        this.posts = response;
      });
    

    您需要做的所有事情,可以说是最好的选择是将帖子设置为响应。它已经是一个 JavaScript 对象了。

    如果出于某种原因您需要 JSON 字符串,那么您可以查看 JSON.Stringify:

     this.posts = JSON.stringify(response)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      相关资源
      最近更新 更多