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

本文介绍如何通过使用不可变状态来确保Angular管道能够正确更新。通过改变引用而非直接修改原有数组的方式,使得管道能够感知到变化并进行更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

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

 

转载于:https://www.cnblogs.com/Answer1215/p/5303551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值