我有两个不同的组件中的两个函数,我想在它们之间共享函数,但是我不知道如何在我的项目中使用它。在组件中,我有一个getDatasFromMainTable().在另一个,我有一个getDatasFromArchiveTable().我试过:
@Input() myFirstComponent!: MyfirstComponent;在一个功能上:
this.myFirstComponent.getDatasFromArchiveTable();但我有个口信
Cannot read properties of undefined (reading 'getDatasFromArchiveTable')我读了很多关于behaviorSubject,或@ lot (),@ViewChild()或onChanges的东西.但如果我需要它的话,我不知道该如何为我的项目鼓掌。
发布于 2022-04-27 13:28:45
这就是服务的目的。
组件应该是“愚蠢的”,因为它们没有任何商业上的意义:它们把责任交给了服务。这就是依赖注入的意义所在。
因此,要共享这些方法,创建包含这些方法的服务,让组件调用服务上的这些方法。
发布于 2022-04-27 14:56:52
您有很多方法可以在组件上共享数据。
通过输入共享数据,通过ViewChild
共享数据,在组件上共享相同的逻辑(方法)
在你的例子中,解决方案将是5。如果你想要共享的方法(一些逻辑,并使用它在整个应用程序中)
简单服务示例:
import { Injectable } from '@angular/core';
@Injectable()
export class ExampleOfService{
constructor() { }
exampleOfFunction() {
doSomething();
}
}之后,您可以在每个组件中调用您的方法。你可以添加参数等等..。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example-component',
template: ['./app-example-component.html'],
styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit{
constructor(private exampleOfService: ExampleOfService) { }
ngOnInit(){
//you can subscribe or whatever you need.
this.exampleOfService.exampleOfFucntion();
}
}https://stackoverflow.com/questions/72029503
复制相似问题