繁体   English   中英

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

[英]Property 'id' does not exist on type 'Object'

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

我有一个错误:

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


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;
          }
        });
  }
}

您需要说响应是any类型以消除该错误,

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

response是一个数组,但您没有名为id的值。 或者它没有达到'id',你可能有多个。

暂无
暂无

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

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