有没有办法从DOM中调用服务定义的函数,我可以从DOM中调用组件函数,但是我们如何调用服务函数,就像这样:
@Injectable()
export class UtilsService {
constructor() {}
getSessionId() {}
}
<button name="getsession" (click)="UtilsService.getSessionId()">Get Session</button>
有没有办法从DOM中调用服务定义的函数,我可以从DOM中调用组件函数,但是我们如何调用服务函数,就像这样:
@Injectable()
export class UtilsService {
constructor() {}
getSessionId() {}
}
<button name="getsession" (click)="UtilsService.getSessionId()">Get Session</button>
视图绑定中表达式的作用范围仅限于组件类实例。无法直接从视图访问静态变量、全局变量、类型(枚举)等。
如果要在视图中引用它,则必须通过组件类实例访问。
constructor(public utilsService:UtilsService) {}
<button name="getsession" (click)="utilsService.getSessionId()">Get Session</button>
<button name="getsession" (click)="getSessionId()">Get Session</button>
Component Class
export class MyComponent {
getSessionId: any;
constructor(private utilsService:UtilsService) {
this.getSessionId = utilsService.getSessionId;
}
}
getSessionId = utilsService.getSessionId;
不应该放在构造函数里吗?无论如何,我会将其设置为setter。我猜你是指 https://en.wikipedia.org/wiki/Law_of_Demeter。 - Günter Zöchbauer