![](/img/trans.png)
[英]Angular pass a component from a module to another module in the App module
[英]Communication from angular module to app component
在我的 angular 客戶端中,我有一個模塊調用庫。 它執行與書籍相關的 CRUD 交易。 我在應用程序根目錄中有一個警報組件和服務。 該警報組件作為視圖子嵌套在 app-component 中。 因此,一旦我執行了 CRUD 操作,我想從我的庫模塊通知 root 中的服務。 誰能幫我找出建立這種溝通的最簡單方法。 先感謝您。
警報服務
import { Injectable } from '@angular/core';
//Alert service
@Injectable({
providedIn: 'root'
})
export class AlertService {
//Attributes
show: boolean = false;
type: string = 'info';
message: string;
timeoutTimer: any;
//Constructor of the AlertService.
constructor() { }
//Responsible for displaying the alert.
displayAlert(message: string, type: string = 'info', autohide: number = 5000) {
this.show = true;
this.message = message;
this.type = type;
//If timer is already available
if (this.timeoutTimer) {
clearTimeout(this.timeoutTimer);
}
//If autohide is there then start the timeout
if (autohide) {
setTimeout(() => {this.close()}, autohide);
}
}
//Responsible for setting the show attribute false.
close() {
this.show = false;
}
}
我要去 select Angular 文檔中的一個例子來解釋這一點。
export class HeroListComponent implements OnInit {
heroes: Hero[] = [];
selectedHero: Hero | undefined;
constructor(private service: HeroService) { }
ngOnInit() {
this.heroes = this.service.getHeroes();
}
selectHero(hero: Hero) { this.selectedHero = hero; }
}
constructor(private service: HeroService)
是將服務注入組件的地方。 你現在可以在你的組件中訪問 HeroService 的所有方法。 因此,您可能希望在服務中創建一個方法,例如alert(message) { doSomething }
,然后在組件中調用service.alert("Hello")
,通常是在執行 CRUD 操作的方法期間。 查看 ngOnInit() function 如何使用該服務及其一種方法來更新組件中的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.