簡體   English   中英

從 Angular 7 中的 API 獲得響應后,如何將一個組件的值傳遞給另一個組件

[英]How to pass value one component to another component after getting response from an API in Angular 7

我正在處理一個 API 問題。 在收到來自 API 的響應后,我想將該值傳遞給子組件。 在那里我將執行方法並獲得響應,並將其顯示在屏幕上。

代碼:

    ngOnInit() {
            const userId = '2';
            this.apiService.collectIds(userId)
            .subscribe(ids => {
                this.ids = ids
            }, error => {
                console.log('error', error);
            });
        }

子組件:

    <app-chart [ids]="ids"></app-chart>

父子組件之間最常見的通信方式是使用@Input@Output裝飾器。

對於您的特定情況,您必須使用@Input裝飾器

在您的子組件 app-chart 中,您可以這樣聲明:

@Input() ids: number; // Or which ever the type you have

在您的示例中,您從服務中獲取價值。 當子組件中的 @Input 元素在父組件中發生變化時,Angular 會自動更新它。 如果您不必對輸入的更改(在子組件中)執行任何方法,則不必執行任何其他操作(例如訂閱、異步管道等)。

你有沒有嘗試在視圖中放置異步?

<app-chart [ids]="ids | async"></app-chart>

更多關於異步使用https://angular.io/api/common/AsyncPipe

試試這個

ngOnInit() {
       const userId = '2';
       this.collectIds$ =  this.apiService.collectIds(userId);
}

在 html 中:

<app-chart [ids]="(collectIds$|async)?.ids"></app-chart>

暫無
暫無

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

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