我想重用一个角函数,它可以改变多个组件的属性(相同类型)。第一个解决方案是将此函数作为全局变量导入。
Utilis.ts
export function alterProperty(property: CustomProperty) {
.... // some change on property
}component.ts
import {alterProperty} from './Utilis.ts'
class MyComponent {
property1: CustomProperty;
constructor(){}
handleClick() {
alterProperty(this.property1);
}
}在我读了一些关于角度依赖注入的文章之后,我意识到这可能不是一个好的解决方案,所以我想出了另一个解决方案。
myService.ts
@Injectable()
export class MyService1 {
constructor(){}
alterProperty(property: CustomProperty)
} component.ts
import MyService1 from 'myService.ts'
@Component{
providers: [MyService1]
}
export class MyComponent {
property1: CustomProperty;
constructor(private service1:MyService1){}
handleClick(){
this.service1.alterProperty(this.property1);
}
}以下是我的问题:
感谢你的建议。
发布于 2018-03-15 14:47:49
答1. )您可以在src下的共享目录中拥有一个服务或实用程序。此服务中的函数将负责更改属性。
回答2. )AFAIK,共享服务是一种有效的解决方案。只要需要,就会将其注入组件。也许有更好的解决办法,但这个也不是不正确的。
https://stackoverflow.com/questions/49302361
复制相似问题