首页 文章

从实现自定义接口的多层对象绑定到角度2中的视图

提问于
浏览
0

我试图将对象中的变量绑定到我的视图中 .

我已经导入了所有需要导入的内容 - 我为路由实现了一个解析器,以便在加载视图之前获取数据 .

如果我在HTML中绑定 {{ test | json }} ,我会获得完整的对象和子对象(全部3层) .

如果我绑定 {{ test.abc.def }} 我收到错误 . 无法读取未定义的属性'def' .

export class TestComponent implements OnInit {
    public test: ABCTest = this.route.snapshot.data as ABCTest;
}

我试图从我的组件代码(在ngOnInit函数内)到达它,我得到abc是未定义的 . 虽然如果我记录this.route.snapshot.data我在控制台中获得了完整的对象,我可以打开子对象并查看它们 .

我的界面看起来像这样:

export interface ABCTest {
    abc?: {
        def?: string;
    }
    ....
}

有关如何访问子对象的任何帮助 .

2 回答

  • 0

    通过我在解析器中识别的变量正确地获取快照数据后,我能够访问数据 .

    让我们说解决方案对象如下:

    {
            test: testResolver
    }
    

    要访问我使用的数据:test = this.route.snapshot.data [“test”]作为TestInterface

    然后我在我的html中使用了test.abc.def .

  • 0

    试试这个 . 刚做了快速测试,它对我来说很好 .

    export interface ABCTest {
        abc?: {
            def?: string;
        }
        ....
    }
    

    类声明:

    export class TestComponent implements OnInit {
    
      public test: ABCTest;
    
      ngOnInit() {
        this.test = this.route.snapshot.data as ABCTest;
      }
    }
    

相关问题