Angular 2在尝试将元素添加到数组时尝试diff'3'时出错

时间:2016-07-08 01:01:28

标签: angularjs typescript angular

list.component

import { Component, OnInit } from '@angular/core';
import { Todo } from '../model/todo';
import { TodoDetailComponent } from './detail.component';
import { TodoService } from '../service/todo.service';


@Component({
    selector: 'my-todos',
    styleUrls: ['/app/todo/styles/list.css'],
    templateUrl:'/app/todo/templates/list.html',
    directives: [[TodoDetailComponent]],
    providers: []
})

export class ListComponent implements OnInit {
    public todos: Todo[];
    title = 'List of Todos';
    selectedTodo: Todo;
    newTodo: string;

    constructor(private todoService: TodoService) {

    }
    ngOnInit() {
        this.getTodos();
    }
    addTodo() {
        this.todoService.addTodo(this.newTodo).then(
            todos => this.todos = todos
        );
    }
    getTodos() {
        TodoService.getTodos().then(
            todos => this.todos = todos
        );
    }
    onSelect(todo: Todo) {
        this.selectedTodo = todo;
    }
}

todo.service

import { Injectable } from '@angular/core';
import { Todo } from '../model/todo';
import { TODOS } from './mock-todos';

@Injectable()
export class TodoService {
    static getTodos() {
        return Promise.resolve(TODOS).then(
            todos => todos
        );
    }
    getTodo(id: number) {
        return Promise.resolve(TODOS).then(
            todos => todos.filter(todo => todo.id === id)[0]
        );
    }
    addTodo(task: string) {
        return Promise.resolve(TODOS).then(
            todos => todos.push(new Todo(TODOS.length+1, task))
        );
    }
}

从组件调用addTodo()时出现此错误:

Angular 2 Error trying to diff '3' when trying to add element to array

我已经过了几次,仍然不知道发生了什么。

以下是TODOS

的定义
import { Todo } from '../model/todo';

export var TODOS: Todo[] = [
    { id: 1, task: 'Do something' },
    { id: 2, task: 'Do something else' }
];

我有一个触发模板中addTodo()的按钮。

1 个答案:

答案 0 :(得分:4)

Angular使用diffchecker 每当列表更改其值时 - 验证列表中的项目以及添加了哪些项目。

发生错误是因为您可能正在尝试迭代(例如,使用*ngFor)数字3,这不是集合。

换句话说,从错误消息中,您应该是集合的变量是值3

您的案例

由于在您致电ListComponent#addTodo()时会抛出异常:

public todos: Todo[];
...
addTodo() {
    this.todoService.addTodo(this.newTodo).then(
        todos => this.todos = todos
    );
}

您可能正在3将值this.todos分配给todos => this.todos = todos

了解上述情况后,我们必须找出您的服务因3调用而返回addTodo()的原因。

看看TodoService#addTodo()

addTodo(task: string) {
    return Promise.resolve(TODOS).then(
        todos => todos.push(new Todo(TODOS.length+1, task))
    );
}

您会注意到该方法实际上返回了push()的结果 - 这是推送后数组的长度。并且因为它向TODOS模拟数组添加了一个元素,所以在推送后它将有三个元素,因此返回3

修复

要使一切正常,请为*ngFor使用的变量指定一个集合,而不是数字3

在您的情况下,由于分配给它的值是服务返回的值,只需让它返回数组:

addTodo(task: string) {
    return Promise.resolve(TODOS).then(
        todos => {
          todos.push(new Todo(TODOS.length+1, task));
          return todos;                                  /// ------------- added this line
        }
    );
}