简体   繁体   English

如何使用 .subscribe in angular 为数组赋值?

[英]how to assign values to an array using .subscribe in angular?

I am using a HttpClient calling.I am trying to assign values to posts[] which i hav defined as type any.我正在使用 HttpClient 调用。我试图将值分配给我定义为任何类型的帖子 []。

I am getting error as follows:我收到如下错误:

The 'Object' type is assignable to very few other types. “对象”类型可分配给很少的其他类型。 Did you mean to use the 'any' type instead?您是想改用“any”类型吗? Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.类型“Object”缺少来自“any[]”类型的以下属性:length、pop、push、concat 等 26 个。

My code for posts.component.html我的 posts.component.html 代码

import { Component, OnInit } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

  posts: any[];

  constructor(http:HttpClient) { 

    http.get('http://jsonplaceholder.typicode.com/posts').subscribe(response =>{
      this.posts=response;})
  }

  ngOnInit(): void {
  }

}

You have to specify the type of the response:您必须指定响应的类型:

http.get<any[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
  this.posts = response;
})

You should type your httpClient.get method call, like this:您应该键入httpClient.get方法调用,如下所示:

http.get<any[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
   this.posts = response;
})

Best practice is also to create an interface for your model, for example:最佳实践也是为您的模型创建一个interface ,例如:

export interface Post {
  id: number,
  title: string,
  ...
}

So your code could be :所以你的代码可能是:

export class PostsComponent implements OnInit {
  posts: Post[];

  constructor(http: HttpClient) { 

    http.get<Post[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
      this.posts = response;
    })
  }

  ngOnInit(): void {
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM