1

请帮助一个新手。我ngStorage用来存储一些全局变量:

//Global Controller
saveGlobalSettings = () => {
        this.$sessionStorage.QuoteTimes = this.quoteTimes;
        this.$sessionStorage.QuoteTypes = this.quoteTypes;
    };

我在另一个控制器中使用另一种方法来创建使用一些全局变量作为属性的对象:

// Create Controller 
addChannel = (channel) => {            
        channel.QuotingChannelType = channel.QuotingChannelId;             
        console.log(this.$sessionStorage.QuoteTimes);
        channel.QuoteTypes = this.$sessionStorage.QuoteTypes;
        channel.QuoteTimes = this.$sessionStorage.QuoteTimes;
        if (!this.myChannels) { this.myChannels = []; }
        this.myChannels.push(channel);           
    };

然后我用来在浏览器ng-repeat中显示对象。myChannels单击时,我将对象传递给openDialog()方法:

 openPreferencesDialog = (channel) => {
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };            
        this.$uibModal.open(options).result
            .then(updatedChannel => console.log(updatedChannel));               
    };

对话框按预期打开,但是当我进行更改时,它正在更新inQuoteTimesQuoteTypes数组$sessionStorage(从console.login看到addChannel)。所以创建的每个新对象都有我编辑的最后一个对象的QuoteTimesQuoteTypes。我完全被难住了。我最好的猜测是它是某种范围链问题?知道我做错了什么吗?

更新:我能够通过使用JSON.parse(JSON.stringify(obj));如下方式使其按预期工作:

openPreferencesDialog = (obj, index) => {           
        var channel = JSON.parse(JSON.stringify(obj));
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };            
        this.$uibModal.open(options).result
            .then(updatedChannel =>
            {
                console.log(updatedChannel);
                this.$sessionStorage.myChannels[index].QuoteTimes = updatedChannel.QuoteTimes;
                this.$sessionStorage.myChannels[index].QuoteTypes = updatedChannel.QuoteTypes;
                console.log(this.$sessionStorage.myChannels)
            });               
    };

谁能解释为什么这有效?

4

1 回答 1

1

如果quote...频道对象的成员不是原始类型,这是正常行为。因为它们是最后编辑的通道对象和 $sessionstorage 在内存中对它们具有相同引用的引用类型。

于 2017-03-31T21:03:21.850 回答