首页 > 解决方案 > “对象”类型上不存在属性“待办事项”

问题描述

我正在构建我的第一个 MEAN 堆栈来做应用程序。我希望我正确地表达了我的问题,因为我对此并不陌生。

错误来自我的 getList().subscribe 函数。我想我明白错误试图告诉我什么,但我不知道如何解决它。我试过分配

todos: any;

但这没有用。然后我尝试分配

todos: Array<any>;

以及许多其他不同的语法;没运气。

仪表板.component.ts

export class DashboardComponent implements OnInit {
  user: Object;

  lists: any;
  todos: any;

  @Input() input;

  @Output() update = new EventEmitter();

  constructor(
    private authService: AuthService,
    private flashMessage: FlashMessagesService,
    private listService: ListService
  ) { }

  ngOnInit() {
    this.getLists();

    this.authService.getProfile().subscribe(profile => {
      this.user = profile.user;
    },
    err => {
      console.log(err);
      return false;
    });
  }

  getLists(): void {
    this.listService.getAllTodos()
      .subscribe(data => this.lists = data.todos);
  }

列表.service.ts

export class ListService {
  newTodo: any;
  list: any;

  constructor(private http: HttpClient) { }

  getAllTodos() {
    return this.http.get('http://localhost:3000/todos/lists');
  }

编辑 =================================================== =

这是我尝试的自定义接口/类模型以及我订阅可观察对象的更改编码

列表.ts

export class List {
  item: string;
  completed: boolean;
}

更改为我的旧文件

仪表板.component.ts

import { List } from '../../list';

export class DashboardComponent implements OnInit {

  lists: List;

getLists(): void {
    this.listService.getAllTodos()
      .subscribe((data: List) => this.lists = data.todos);
  }

除了类型从“对象”更改为“列表”之外,我仍然在主题行中发布了相同的错误

Property 'todos' does not exist on type 'List'

标签: angularrestmean-stack

解决方案


您可以自定义interface/class映射响应。或者在访问 todos 之前使用 any 类型。

 this.listService.getAllTodos()
      .subscribe((data:any) => this.lists = data.todos);

推荐阅读