在intanciate类上传递嵌套对象

时间:2018-02-19 20:19:29

标签: rxjs behaviorsubject

当我尝试在新的Class()上传递嵌套对象时,它返回空类。

我认为这是因为我传递错误的论据。

class myClass {
    public selected: {
        category: {
            code: string
        }
    } = {}
}

const initialState = {
    selected: {
        category: {
            code: ''
        }
    }
}

private bs: BehaviorSubject<any> = new BehaviorSubject(initialState)

这项工作很好,我给myClass带来了价值。

但是当我想在之后传递值时:

setCategory (myCategory) {
    let value = this.bs.getValue();
    let newValue = Object.assign({}, value, {
                    selected: {
                        category:{
                            code: myCategory
                        }
                    }
                });
     new myClass(newValue) // return { view: {}, selected: { category: { code: '' } } }
}

我得到{ view: {}, selected: { category: { code: '' } } }

更新

直播代码:https://stackblitz.com/edit/angular-bjlhus?file=app%2Fapp.component.ts

1 个答案:

答案 0 :(得分:1)

您需要将构造函数添加到类中,以将输入参数分配给selected属性:

constructor(state) {
    this.selected = state.selected;
}

这是带有修复的stackblitz:https://stackblitz.com/edit/angular-hokh2a