Angular中ng-template Outlet上下文注入服务未定义的解决方法
解决方案
这个问题本质是函数传递时this指向丢失导致的:当你把action函数传到ngTemplateOutletContext后,按钮点击调用它时,this不再指向组件实例,自然访问不到myService。以下是两种规范的解决方法:
方法一:用箭头函数定义action
箭头函数不会绑定自己的this,会继承外层组件的上下文,直接修改组件里的action定义:
export class MyComponent implements OnInit { constructor(public myService: MyService) { } ngOnInit() { } // 改成箭头函数 action = () => { this.myService.doSomething(); } }
模板部分不需要修改,传递这个箭头函数后,点击按钮时this依然指向组件实例,能正常访问myService。
方法二:显式绑定this到函数
在组件构造函数里,用bind把action函数的this绑定到组件实例:
export class MyComponent implements OnInit { constructor(public myService: MyService) { // 绑定this到组件实例 this.action = this.action.bind(this); } ngOnInit() { } action() { this.myService.doSomething(); } }
这种方式也能确保传递后的函数调用时,this指向正确的组件实例。
为什么之前的写法会报错?
普通函数的this指向是由调用方式决定的:当你把action作为值传递到上下文后,按钮点击时是直接调用这个函数,此时this在严格模式下会变成undefined,所以this.myService就会抛出Cannot read property 'doSomething' of undefined的错误。
内容的提问来源于stack exchange,提问作者Rich
相关产品推荐
相关产品推荐

