[英]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.