我有一个将函数作为输入的组件。我已经从父级传递了这个函数。
尽管调用了该函数,但该函数无法访问声明该函数的实例的依赖关系。
这是组件
@Component({
selector: 'custom-element',
template: `
{{val}}
`
})
export class CustomElement {
@Input() valFn: () => string;
get val(): string {
return this.valFn();
}
}
这是组件的使用方式
@Injectable()
export class CustomService {
getVal(): string {
return 'Hello world';
}
}
@Component({
selector: 'my-app',
template: `
<custom-element [valFn]="customVal"></custom-element>
`,
})
export class App {
constructor(private service: CustomService) {
}
customVal(): string {
return this.service.getVal();
}
}
当我运行这个应用程序时,我在控制台中收到一条错误消息Cannot read property 'getVal' of undefined
这是这个问题的一个小问题。