【问题标题】:Property 'id' does not exist on type 'Object'“对象”类型上不存在属性“id”
【发布时间】:2019-10-11 01:50:06
【问题描述】:

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

我有一个错误:

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

【问题讨论】:

  • response 是一个数组吗?你应该检查这个

标签: angular typescript


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      • 2018-02-10
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多