【问题标题】:Angular - Type 'Object' is missing the following properties from type when doing http getAngular - 类型“对象”在执行 http get 时缺少类型中的以下属性
【发布时间】:2020-07-09 00:31:59
【问题描述】:

我使用 jsonplaceholder 渲染到列表中创建了假 API。我得到了我所期望的输出,但是一个编译器错误如下我得到了我所期望的输出,但是一个编译器错误**

src/app/posts/posts.component.ts:14:8 中的错误 - 错误 TS2696:“对象”类型可分配给极少数其他类型。您的意思是改用“任何”类型吗? “Object”类型缺少“any[]”类型的以下属性:length、pop、push、concat 等 26 个。

 14        this.posts = response;

这是我的 .ts

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

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

这是我的模板文件

    <ul class="list-group">
        <li  
        *ngFor="let post of posts" 
        class="list-group-item">
            {{post.body}}
        </li>
    </ul>

【问题讨论】:

标签: angular http-get


【解决方案1】:

Typescript 是一种类型化语言(但仍编译为 js)。所以你可能没有在服务中指定你得到什么类型的对象作为响应(在方法头或.get&lt;&gt;泛型方法中)。你不应该使用any,而是创建你自己的类来代表你得到的响应结构(或js对象)。

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2023-03-11
    • 2021-04-20
    • 2021-07-29
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多