我試圖從我的第二個組件中的發射值中獲取資料引數的值
這是我的代碼
組件 1 TS
this.myService.emitChange({emitValue: 'openFunctionInSidePanel', data: data });
組件 2 服務檔案
private emitChangeSource = new Subject<any>();
changeEmitted$ = this.emitChangeSource.asObservable();
emitChange(event) {
this.emitChangeSource.next(event);
}
組件 2 TS
console.log(this.myService.emitChange);
那么如何在組件 2.ts 檔案中獲取實際資料值呢?
我目前看到
? (event) {
this.emitChangeSource.next(event);
}
uj5u.com熱心網友回復:
您需要“訂閱”更改Emitted$。
你可以在 ngOnInit
//don't forget unsubscribe!!!
ngOnInit()
{
this.myService.changeEmitted$.subscribe((res:any)=>{
console.log(res)
})
}
或者,如果只想顯示結果,您可以使用管道異步
您可以在建構式中將服務宣告為公共
constructor(public myService:MyService){}
//in html
<div *ngIf="myService.changeEmitted$|async as value">
{{value.emitValue}} - {{value.data|json}}
</div>
或宣告為私有并使用輔助變數
changeService$=this.myService.changeEmitted$
constructor(private myService:MyService){}
//in html
<div *ngIf="changeService$|async as value">
{{value.emitValue}} - {{value.data|json}}
</div>
注意:您還可以使用 rxjs 運算子“玩”,例如過濾回應并轉換為僅回傳“資料”
changeService$=this.myService.changeEmitted$.pipe(
filter((res:any)=>res.emitValue=='openFunctionInSidePanel'),
map((res:any)=>res.data)
)
//then subscribe to this.changeService or use in .html `{{changeService|async}}`
注意:我添加了一個回應,因為文章在另一個答案中指出不要考慮異步管道
uj5u.com熱心網友回復:
基本上,這兩個組件之間應該有一個共享服務。使用服務從組件 1 發出值,并使用共享服務從組件 2 訂閱值。
請參閱本文的第 4 種方法,該方法展示了如何在不相關的組件之間傳遞資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527715.html
標籤:有角度的
下一篇:在AWS上部署后端和前端