类型“对象”上不存在属性“ id”

时间:2019-05-24 12:45:12

标签: angular typescript

我想知道是否可以提供帮助。我正在这门课程https://www.udemy.com/the-complete-angular-master-class/learn/lecture/7441148#questions

我有一个错误:

  src / app / posts / posts.component.ts(21,11)中的

ERROR:错误TS2696:    “对象”类型可分配给很少的其他类型。您是不是要使用>'any'类型?     类型“ Object”缺少类型“ any []”中的以下属性:length,pop,push,concat和26个以上属性。   src / app / posts / posts.component.ts(32,33):错误TS2339:类型“ Object”上不存在属性“ id”。


import { BadInput } from './../common/bad-input';
import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
import { PostService } from './../services/post.service';
import { Component, OnInit } from '@angular/core';

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

  constructor(private service: PostService) {}

  ngOnInit() {
    this.service.getPosts()
      .subscribe(
        response => {
          this.posts = response
        });
  }

  createPost(input: HTMLInputElement) {
    let post : any = { id: null, title: input.value };
    input.value = '';

    this.service.createPost(post)
      .subscribe(
        response => {
          post['id'] = response.id;
          this.posts.splice(0, 0, post);
          console.log(response);
        }, 
        (error: AppError) => {
          if (error instanceof BadInput) {
            //this.form.setErrors(error.originalError)
          } else {
            throw error;
          }
        });
  }

  updatePost(post) {
    this.service.updatePost(post)
      .subscribe(
        response => {
          console.log(response);
        });
  }

  deletePost(post) {
    this.service.deletePost(99999)
      .subscribe(
        response => {
          let index = this.posts.indexOf(post);
          this.posts.splice(index, 1);
        },
        (error: AppError) => {
          if (error instanceof NotFoundError) {
            console.log(error);
          } else {
            throw error;
          }
        });
  }
}

2 个答案:

答案 0 :(得分:0)

您需要说响应的类型为any才能消除该错误,

this.service.createPost(post)
      .subscribe(
        (response :any) => {

答案 1 :(得分:0)

响应是一个数组,但是没有名为id的值。否则无法达到“ id”,您可能会有多个。