[英]Calling component from service - angular
我已经尝试了一些方法,但到目前为止似乎都没有。 我试图在另一个组件中的单击事件中调用一个组件中的 function。 我在控制台中没有任何错误。
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!!!");
});
}
}
我从来没有打过console.log
。
您可以使用 RXJS 导入主题
第一个组件
constructor(public projectService: ProjectOverviewService) { }
delete(event) {
this.projectService.invokeFirstComponentFunction.next();
}
服务
public invokeFirstComponentFunction = new Subject();
第二部分
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()
}
如果您计划使用服务在 2 个组件之间建立通信,那么事件发射器不是方法。 这就是我要做的:
第一个组件
constructor(public projectService: ProjectOverviewService) { }
delete(event) {
this.projectService.onFirstComponentButtonClick("Name");
}
服务
invokeFirstComponentFunction = new Subject<string>();
subs$ = this.invokeFirstComponentFunction.asObservable();
onFirstComponentButtonClick(name: string) {
this.invokeFirstComponentFunction.next(name);
}
第二部分
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.