Angular2报错TS2339:BookComponent类型上不存在属性posts如何解决
报错根因
Angular 组件模板的变量默认绑定当前组件类的属性,你写在book.component.html里的<li *ngFor="let post of posts">属于BookComponent的模板内容,而BookComponent类中并没有定义posts属性,posts是PostComponent类的私有属性,不能直接在父组件模板中访问。
你放在<post>标签内部的内容属于「内容投影」,作用域仍然归属父组件BookComponent,不会自动继承子组件的属性。
解决方案(推荐第一种,符合组件职责分离原则)
方案1:把列表逻辑迁移到PostComponent自有模板
这是最合理的方案,因为posts本身就是PostComponent维护的数据,列表渲染逻辑应该内聚在PostComponent内部:
- 修改
book.component.html,清空<post>标签内部的内容,仅保留组件调用:
<post></post>
- 把你写在
<post>标签里的列表代码,复制到post.component.html文件中即可,此时模板访问的posts就是当前PostComponent类的属性,不会再报错。
方案2:如果确实需要在父组件中渲染列表
如果业务要求必须把列表内容放在BookComponent中写,你需要让BookComponent自己维护posts数据:
- 在
BookComponent类中定义posts属性,复制PostComponent中的http请求逻辑到BookComponent中获取posts数据即可。
优化建议
- 给
posts变量定义明确的类型,比如posts: any[] = [],或者自定义Post接口声明类型,避免后续类型报错 - 不要把http请求写在组件构造函数中,构造函数仅用于依赖注入,业务逻辑建议放到
ngOnInit生命周期钩子中执行 - 及时取消Observable的订阅避免内存泄漏,简单场景可以直接用
async管道自动处理订阅和销毁。
内容的提问来源于stack exchange,提问作者Lee Z
相关产品推荐
相关产品推荐

