angular - 类型 'id' 上不存在属性 'Object'

标签 angular typescript

我想知道你是否可以帮忙。我正在关注这门类(class)https://www.udemy.com/the-complete-angular-master-class/learn/lecture/7441148#questions

我有一个错误:

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

最佳答案

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

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

关于angular - 类型 'id' 上不存在属性 'Object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292980/

相关文章:

javascript - 在发送到后端时显示数据

Angularfire2读取数据一次

javascript - 我想从在垫复选框中选中的项目中列出一个列表

javascript - Angular 5 从服务到组件到模板的数据获取数组问题

javascript - Angular2 在创建 ngSwitch 新 View 后调用自定义函数

node.js - 无法从 Node 服务器打开 Angular 构建应用程序

javascript - Typescript/Javascript - 使用 new String() 和 s = '' 声明变量

Node.js - 语法错误 : Unexpected token * when import express

TypeScript:在多个文件中声明类的函数

angular - 如何在map之前在rxjs中保存值