[英]Calling component from service - angular
I already tried a few approaches but none of them seems to work so far.我已经尝试了一些方法,但到目前为止似乎都没有。 I am trying to call a function in one component on click event in another component.
我试图在另一个组件中的单击事件中调用一个组件中的 function。 I don't have any errors in the console.
我在控制台中没有任何错误。
constructor(public projectService: ProjectOverviewService) { }
delete(event) {
this.projectService.onFirstComponentButtonClick();
}
invokeFirstComponentFunction = new EventEmitter();
subsVar: Subscription;
onFirstComponentButtonClick() {
this.invokeFirstComponentFunction.emit();
}
constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
if (this.projectOverviewService.subsVar == undefined) {
this.projectOverviewService.subsVar = this.projectOverviewService.
invokeFirstComponentFunction.subscribe((name: string) => {
console.log("I am here!!!");
});
}
}
I am not hitting console.log
ever.我从来没有打过
console.log
。
You can use RXJS import Subject您可以使用 RXJS 导入主题
First component第一个组件
constructor(public projectService: ProjectOverviewService) { }
delete(event) {
this.projectService.invokeFirstComponentFunction.next();
}
Service服务
public invokeFirstComponentFunction = new Subject();
Second Component第二部分
subsVar: Subscription;
constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
this.subsVar = this.projectOverviewService.invokeFirstComponentFunction.
.subscribe(() => {
console.log("I am here!!!");
});
}
ngOnDestroy(){
this.subsVar && this.subsVar.unsbscribe()
}
If you are planning to establish communication between 2 components using a service, then event-emitter is not the approach.如果您计划使用服务在 2 个组件之间建立通信,那么事件发射器不是方法。 This is what I would do:
这就是我要做的:
First component第一个组件
constructor(public projectService: ProjectOverviewService) { }
delete(event) {
this.projectService.onFirstComponentButtonClick("Name");
}
Service服务
invokeFirstComponentFunction = new Subject<string>();
subs$ = this.invokeFirstComponentFunction.asObservable();
onFirstComponentButtonClick(name: string) {
this.invokeFirstComponentFunction.next(name);
}
Second component第二部分
constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
this.projectOverviewService.subs$.subscribe((name: string) => {
console.log("I am here!!!");
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.