要让Angular组件能够从服务中看到函数,可以使用依赖注入将服务注入到组件中。
以下是一个解决方法的示例:
my-service.service.ts
,并在其中定义一个函数myFunction
:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
myFunction() {
// 在这里定义服务中的函数逻辑
}
}
import { Component } from '@angular/core';
import { MyService } from './my-service.service';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
constructor(private myService: MyService) {}
callMyFunction() {
this.myService.myFunction();
}
}
在上述示例中,MyService
服务被注入到MyComponent
组件中,并通过调用myService.myFunction()
来调用服务中的函数。
确保在组件的模板中使用了相应的事件绑定,以调用callMyFunction()
函数。