簡體   English   中英

Angular-使用routerLink在父組件上獲取事件

[英]Angular - Get Event on Parent Component using routerLink

我正在像這樣從子組件父組件 發出 事件

子組件

export class ItemComponent {

  @Output() id = new EventEmitter()

  deleteProduct(id) {
    this.id.emit(id)
  }

}

子組件標簽

<app-product-item (id)="getId($event)"></app-product-item>

在我的父組件上接收事件

getId(id){
  console.log(id)
}

一切正常。

現在,我需要具有相同的行為,但是要使用我通過routerLink訪問的組件 ,而不要使用諸如<app-product-item (id)="getId($event)"></app-product-item>這樣的標簽不存在,因為我正在通過routerLink訪問它。

路由配置:

const routes: Routes = [
    { path: '', component: WinesComponent },
    { path: 'app-wines', component: WinesComponent },
    { path: 'app-about', component: AboutComponent },
    { path: 'app-wine-detail/:id', component: WineDetailComponent },
    { path: 'app-wine-add', component: WineAddComponent }
];

您可以通過服務將數據傳遞到需要從中訪問數據的組件。

https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

您可以使用BehaviorSubject從RxJs從一個組件與另一組件發射/觸發事件。

假設我們有一個名為common.service.ts的服務文件

從“ @ angular / core”導入{可注射}; 從'rxjs'導入{BehaviorSubject};

 @Injectable({ providedIn: 'root' }) export class CommonService { constructor() { } // Observable User details private id = new BehaviorSubject<any>(''); id$ = this.id.asObservable(); // user details deleteProduct(id: any) { this.id.next(id); } } 

child.component.ts

從“ ../common.service”導入{CommonService};

構造函數(private commonService:CommonService){this.commonService.deleteProduct(100); //示例ID = 100}

parent.component.ts

從“ ../common.service”導入{CommonService};

構造函數(private commonService:CommonService){this.commonService.id $ .subscribe((id)=> {//這里是從子組件console.log(id);收到的id = 100)}); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM