一种解决方法是使用Angular Service。将共享的函数作为Service的方法的一部分,并将Service注入到组件中以获取共享函数的访问。这样,当函数需要更改时,只需要更新Service中的代码即可,而所有使用该Service的组件将自动更新。
示例代码:
// service file import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' }) export class SharedService {
sharedFunction() { console.log('This is a shared function.'); }
}
// component file import { Component } from '@angular/core'; import { SharedService } from './shared.service';
@Component({
selector: 'app-home',
template:
,
})
export class HomeComponent {
constructor(private sharedService: SharedService) {}Home Component
sharedFunction() { this.sharedService.sharedFunction(); } }
// another component file import { Component } from '@angular/core'; import { SharedService } from './shared.service';
@Component({
selector: 'app-about',
template:
,
})
export class AboutComponent {
constructor(private sharedService: SharedService) {}About Component
sharedFunction() { this.sharedService.sharedFunction(); } }
在这个例子中,SharedService
类定义了名为sharedFunction()
的共享函数。HomeComponent
和AboutComponent
组件都需要使用该函数,所以它们都注入了SharedService
。
在每个组件中,sharedFunction()
方法被定义为使用this.sharedService.sharedFunction()
调用。这使得SharedService
中定义的同名函数可以在组件中共享且不需要重复定义。
注意:如果在组件中不使用@Input或@Output连接两个组件,则使用Service。但是,如果在组件之间传递数据,则