【问题标题】:Cant access nested object's method无法访问嵌套对象的方法
【发布时间】:2019-10-09 07:15:03
【问题描述】:

我有这样的对象:

export class Foo {
    prop1: string;
    prop2: boolean;

    get computedProp() {
        return 'some computed data';
    }

    constructor(init?: Partial<Foo>) {
        Object.assign(this, init);
    }
}

export class Bar {
    propA: any;
    propFoo: Foo;

    constructor(init?: Partial<Bar>) {
        this.propFoo = new Foo();

        Object.assign(this, init);
    }
}

我会这样使用:

export class MyComponent {

    private _propBar: Bar;
    get propBar() {
        return this._propBar;
    }
    @Input propBar(value: Bar) {
        // value is a json data fetched from api for example
        this._propBar = new Bar(value);
    }

}

这应该创建一个新的 Bar() 对象并允许我访问所有属性,但 Foo 属性未正确构建,因此无法访问 computedPro 并在 html 中的数据绑定中给我错误。

我尝试了https://www.npmjs.com/package/class-transformer?activeTab=readme 包,但效果不佳。

有什么想法吗?我错过了什么?

谢谢

我创建了这个 stackblitz 来说明这个问题: https://stackblitz.com/edit/angular-xtgu6v?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

    标签: angular data-binding


    【解决方案1】:

    在您的演示代码中,您必须将 Bar 构造函数更改为

    constructor(init?: Partial<Bar>) {
        Object.assign(this, init);
        this.foo=new Foo(init.foo); // you will need to assign new foo object here else it will assign  {propA: 5, propB: 10 } to foo and sum will be undef
      }
    

    而不是

     constructor(init?: Partial<Bar>) {
            Object.assign(this, init);
          }
    

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多