简体   繁体   中英

Property 'id' does not exist on type 'Object'

im wondering if you can help. I'm following this course https://www.udemy.com/the-complete-angular-master-class/learn/lecture/7441148#questions

I have an error:

ERROR in src/app/posts/posts.component.ts(21,11): error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the > 'any' type instead? Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more. src/app/posts/posts.component.ts(32,33): error TS2339: Property 'id' does not exist on type '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;
          }
        });
  }
}

You need to say the response is of type any to get rid of that error,

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

response is an array but you don't have a value called id. Or its not reaching 'id', you may have multiple ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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