[Angular 2] Using Array ...spread to enforce Pipe immutability

Pipes need a new reference or else they will not update their output. In this lesson you will use the Array ...spread operator to create new Array to update pipe output without mutation.

 

Currently on our TodoInput.ts, each time you add a new todo into the list, we can see that the TodoModule get updated, but it not showing in the list, this is because Pipes check the reference, it object reference changes then it will update the Pipe. This is good because it can imrpove the prefermence by saving everytime check whether need to update the pipes.

 

To make pipe update itself, we need everytime pass in a new reference. So immutable state is required, for example we need to change the current code:

    onSubmit() {
        this.todoService.todos.push(this.todoModule);
        // After insert, create new TodoModule
        this.todoModule = new TodoModule();
        console.log(this.todoService.todos);
    }

 

To immutable state:

    onSubmit() {
        this.todoService.addNewTodo(this.todoModule); 
        // After insert, create new TodoModule
        this.todoModule = new TodoModule();
        console.log(this.todoService.todos);
    }

//TodoService.ts:
    addNewTodo(todo){
        this.todos = [...this.todos, todo];
    }

 

-----------------------------------

 

posted @ 2016-03-21 20:35  Zhentiw  阅读(160)  评论(0编辑  收藏  举报