如何在 Angular 中保持另一个组件通用的同时从另一个组件调用函数?
How can I call a function from another component while keeping the other component generic in Angular?
我正在尝试让 component1 触发 component2 中的函数,但 component2 需要保持通用,以便任何组件都可以访问它。在不使其通用的情况下,我的代码如下所示:
组件 1:
@Output() component2function = new EventEmitter<any>();
...
this.component2function.emit({ param1, param2 });
组件 2 选择器:
<component1 (component2function)="component2function($event)"> </component1>
这应该会触发 component2function
,但现在我想在不显式使用 component1
选择器的情况下触发相同的功能,以便 component2function
可以由 component1 以外的组件触发。我该怎么做?
所以你需要一些最低限度的协议,实现的组件有这个方法。您可以通过定义一个接口来实现这一点,该接口由 component1
, ...:[=13=] 继承
interface MyInterface {
component2function: EventEmitter<any>;
}
(来源:)
这样,就不用知道具体是什么组件了,但是可以确定有没有这个方法。
我会将该功能放入共享服务中。这样,您需要做的就是通过每个组件的构造函数提供服务。组件 1、组件 2 和组件 3 然后都可以轻松访问此共享功能。
Service.ts
@Injectible({
providedIn: "root"
})
export class SharedService {
sharedFunction() {
let theSolution = ....;
return theSolution;
}
}
然后在component.ts
@Component({
selector: "component1",
templateUrl: "./component1.component.html",
styleUrls: ["./component1.component.css"]
})
export class Component1 implements OnInit {
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.genericFunction();
}
genericFunction() {
this.sharedService.sharedFunction();
}
}
从那里您可以直接从 html 调用服务函数或从 html 调用组件函数,如上所示。如果您正在管理数据,则共享服务中的状态将更加可预测。
我正在尝试让 component1 触发 component2 中的函数,但 component2 需要保持通用,以便任何组件都可以访问它。在不使其通用的情况下,我的代码如下所示:
组件 1:
@Output() component2function = new EventEmitter<any>();
...
this.component2function.emit({ param1, param2 });
组件 2 选择器:
<component1 (component2function)="component2function($event)"> </component1>
这应该会触发 component2function
,但现在我想在不显式使用 component1
选择器的情况下触发相同的功能,以便 component2function
可以由 component1 以外的组件触发。我该怎么做?
所以你需要一些最低限度的协议,实现的组件有这个方法。您可以通过定义一个接口来实现这一点,该接口由 component1
, ...:[=13=] 继承
interface MyInterface {
component2function: EventEmitter<any>;
}
(来源:
这样,就不用知道具体是什么组件了,但是可以确定有没有这个方法。
我会将该功能放入共享服务中。这样,您需要做的就是通过每个组件的构造函数提供服务。组件 1、组件 2 和组件 3 然后都可以轻松访问此共享功能。
Service.ts
@Injectible({
providedIn: "root"
})
export class SharedService {
sharedFunction() {
let theSolution = ....;
return theSolution;
}
}
然后在component.ts
@Component({
selector: "component1",
templateUrl: "./component1.component.html",
styleUrls: ["./component1.component.css"]
})
export class Component1 implements OnInit {
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.genericFunction();
}
genericFunction() {
this.sharedService.sharedFunction();
}
}
从那里您可以直接从 html 调用服务函数或从 html 调用组件函数,如上所示。如果您正在管理数据,则共享服务中的状态将更加可预测。