【问题标题】:Pass nested object on intanciate class在 intanciate 类上传递嵌套对象
【发布时间】:2018-02-19 20:19:29
【问题描述】:

当我尝试在 new 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

【问题讨论】:

标签: rxjs behaviorsubject


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢! :) 现在,我可以安心睡觉了。
  • 酷!我很高兴能帮上忙:)
猜你喜欢
  • 2013-01-30
  • 1970-01-01
  • 2012-06-13
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 2017-05-06
相关资源
最近更新 更多