[Immutable + AngularJS] Use Immutable .List() for Angular array

本文探讨了在Angular应用中利用Immutable.js确保数据不变性的实践。通过具体实例展示了如何定义不可变的数据结构,并在服务中使用这些结构进行数据操作。特别强调了在控制器层面如何将Immutable数据转换为普通JavaScript数组。
        const stores = Immutable.List([
            {
                name: 'Store42',
                position: {
                    latitude: 61.45,
                    longitude: 23.11,
                },
                address: 'whatever'
            },
            {
                name: 'Store2',
                position: {
                    latitude: 61.48,
                    longitude: 23.87
                },
                address: 'whatever'
            },
            {
                name: 'Store3',
                position: {
                    latitude: 61.41,
                    longitude: 23.76
                },
                address: 'whatever'
            },
            {
                name: 'Store4',
                position: {
                    latitude: 61.42,
                    longitude: 23.40
                },
                address: 'whatever'
            }
        ]);

class StoreService {
    constructor( $q) {
        this.$q = $q;

        this.mockStores = stores;
    }

    getStores( position ) {
        return this.$q( ( resolve )=> {
            return resolve( this.mockStores.toArray() );
        } );
    }
}

export default ( ngModule ) => {
    ngModule.service( 'StoreService', StoreService );
}

 

Try to only keep 'serivce' to deal with Immutable data, controller should have no knowledge about whether the data in mutable type or immutable type.

 

So when return the data to the controller, we sue '.toArray()' method to convert the Immutable data structure to normal Javascript array method.

 

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

 

The reason here we use both 'const' and Immutable is because:

 const _person = {
            name: "Zhentian"
        };

class StoreService {
    constructor(  ) {
        this.person = _person;

        this.person.name = "John";
        console.log(_person.name); // --> John

    }

}

export default ( ngModule ) => {
    ngModule.service( 'StoreService', StoreService );
}

 

In the contructor we define:  '_person' assign to 'this.person', even _person is const type, but when we try to modiy the data thougth this.person object, we found actually we are able to do that.

So the const is not safe when deal with object!

So we still need Immutable to help us to keep data immutable.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值