【问题标题】:how to assign values to an array using .subscribe in angular?如何使用 .subscribe 为数组赋值?
【发布时间】:2020-02-18 17:38:53
【问题描述】:

我正在使用 HttpClient 调用。我正在尝试将值分配给我定义为任何类型的帖子 []。

我收到如下错误:

“对象”类型可分配给极少数其他类型。您的意思是改用“任何”类型吗? “Object”类型缺少“any[]”类型的以下属性:length、pop、push、concat 等 26 个。

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 {
  }

}

【问题讨论】:

  • 您的回复是否包含object
  • 我正在从 URL jsonplaceholder.typicode.com/posts 获取值。
  • 你能在这里打印你在订阅中得到的回复吗?
  • 试着给你的回复一个类型,比如.....subscribe((response: any[]) => { ....

标签: angular


【解决方案1】:

您必须指定响应的类型:

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

【讨论】:

    【解决方案2】:

    你应该输入你的httpClient.get方法调用,像这样:

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

    最佳实践也是为您的模型创建一个interface,例如:

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

    所以你的代码可能是:

    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 {
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2021-10-08
      • 1970-01-01
      相关资源
      最近更新 更多