我试图传递一个函数,该函数将注入的服务引用到outlet上下文中的按钮,但是注入的服务是未定义的。下面是我的代码:
import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template: `
<ng-template
[ngTemplateOutlet]="confirmTestingButton"
[ngTemplateOutletContext]="{ buttonAction: action }">
</ng-template>
<ng-template #confirmTestingButton let-buttonAction="buttonAction">
<button class="btn btn-primary btn-sm ml-5" (click)="buttonAction()">Yes</button>
</ng-template>
`
})
export class MyComponent implements OnInit {
constructor(public myService: MyService) { }
ngOnInit() { }
action() {
this.myService.doSomething();
}
}
注射服务
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {}
doSomething() {
// do something
}
}
当我点击按钮时,我得到一个错误说Cannot read property 'doSomething' of undefined.
我不确定是什么原因造成的。我如何解决这个问题,以便我可以在action
函数中使用注入的服务?
我试图在上下文中添加注入的服务:
@Component({
selector: 'app-my-component',
template: `
<ng-template
[ngTemplateOutlet]="confirmTestingButton"
[ngTemplateOutletContext]="{ buttonAction: action, myService: myService }">
</ng-template>
<ng-template #confirmTestingButton let-buttonAction="buttonAction" let-myService="myService">
<button class="btn btn-primary btn-sm ml-5" (click)="buttonAction()">Yes</button>
</ng-template>
`
})
但仍然没有运气。当我将服务作为button函数的参数传递时,唯一的工作是,这对我来说有点尴尬。
@Component({
selector: 'app-my-component',
template: `
<ng-template
[ngTemplateOutlet]="confirmTestingButton"
[ngTemplateOutletContext]="{ buttonAction: action, myService: myService }">
</ng-template>
<ng-template #confirmTestingButton let-buttonAction="buttonAction" let-myService="myService">
<button class="btn btn-primary btn-sm ml-5" (click)="buttonAction(myService)">Yes</button>
</ng-template>
`
})
export class MyComponent implements OnInit {
constructor(public myService: MyService) { }
ngOnInit() { }
action(myService: MyService) {
myService.doSomething();
}
}
有什么合适的方法吗?
尝试使用箭头函数来维护正确的上下文
action = () => {
this.myService.doSomething();
}
工作示例