【问题标题】:I am learning Angular 4 HTTP online and I am practicing in angular 7 so that is why I am getting this error I think我正在在线学习 Angular 4 HTTP,并且我正在使用 Angular 7 进行练习,所以我认为这就是我收到此错误的原因
【发布时间】:2020-06-28 18:24:36
【问题描述】:
@Component({
  selector: 'posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent  {
posts : any[];
  constructor(http : HttpClient) {
    http.get('https://jsonplaceholder.typicode.com/posts/1')
    .subscribe(response => {
      this.posts = response.json();
    });
    }

   }


错误:“对象”类型上不存在属性“json”。

我正在在线学习 Angular 4 并在 Angular 7 中进行练习,这就是为什么我收到此错误的原因,我想请帮助我摆脱此错误以继续我的课程。

【问题讨论】:

标签: angular


【解决方案1】:

Angular 4 使用@angular/http 作为HttpModule 包来获取数据,较新版本使用@angular/common/http 具有HttpClientModule

HttpClient 已经以 JSON 格式获取数据,因此您实际上不需要 .json() 方法,因为您的响应已经是 json。

@Component({
  selector: "posts",
  templateUrl: "./posts.component.html",
  styleUrls: ["./posts.component.css"]
})
export class PostsComponent {
  posts: any[];
  constructor(http: HttpClient) {
    http
      .get("https://jsonplaceholder.typicode.com/posts/1")
      .subscribe(response => {
        this.posts = response;
      });
  }
}

同样对于未来,最好使用构造函数只注入依赖,并使用OnInit生命周期从API中获取数据

@Component({
  selector: "posts",
  templateUrl: "./posts.component.html",
  styleUrls: ["./posts.component.css"]
})
export class PostsComponent implements OnInit {
  posts: any[];
  constructor(private readonly http: HttpClient) {}

  ngOnInit() {
    this.http
      .get("https://jsonplaceholder.typicode.com/posts/1")
      .subscribe(response => {
        this.posts = response;
      });
  }
}

基于从 json 占位符带来的帖子类型,这是一个正确的方法:

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

@Component({
  selector: "posts",
  templateUrl: "./posts.component.html",
  styleUrls: ["./posts.component.css"]
})
export class PostsComponent implements OnInit {
  post: Post;
  constructor(private readonly http: HttpClient) {}

  ngOnInit() {
    this.http
      .get<Post>("https://jsonplaceholder.typicode.com/posts/1")
      .subscribe(response => {
        this.post = response;
      });
  }
}

更新。已添加Stackblitz 示例。

【讨论】:

  • 我收到上面代码的这个错误。 “对象”类型可分配给极少数其他类型。您的意思是改用“任何”类型吗? “Object”类型缺少“any[]”类型的以下属性:length、pop、push、concat 等 26 个。
  • 是的,所以如果您打开jsonplaceholder.typicode.com/posts/1,它会返回一个对象,而不是多个对象。所以any[] 不起作用。让我更新我的答案
  • 我确实做到了。看看最后的代码 sn -p @Josey :)
  • 我既没有收到错误也没有输出,所以你能说一下你在 app-html 代码中做了什么,因为我不确定我错在哪里
  • @Josey 我已经添加了 Stackblitz 示例,它稍微高级一些——它使用异步管道订阅 observables(这是最佳实践)。还演示了如何将哑(仅取决于输入)组件与从外部世界获取数据的组件分开。
猜你喜欢
  • 2013-10-08
  • 2022-10-14
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 2018-07-16
相关资源
最近更新 更多