簡體   English   中英

使用@Input 將異步值從父組件傳遞到子組件

[英]Passing asynchronous value from parent to child component with @Input

我正在嘗試以角度 7 傳遞來自 api、從父組件到子組件的映射。

父母.ts

export class AppComponent {
  title = 'taurs-frontend';
  categories: any;
  isLoggedIn = false;

ngOnInit(){
    this.roomDataService.getData(`${environment.api_url}/api/Categories`)
    .subscribe(categories => {
      this.categories=categories
    }); 
  }

父.html

 <app-room-card [categories]="categories"></app-room-card> 

孩子.ts

@Component({
  selector: 'app-room-card',
  templateUrl: './room-card.component.html',
  styleUrls: ['./room-card.component.css']
})
export class RoomCardComponent implements OnInit {
    @Input('categories') catname: any;

    ngOnInit() {
        console.log('aaa'+ this.catname);
    }
// ..
}

當我嘗試記錄變量catname ,它是undefined 如果我嘗試從父項導入變量標題,則一切正常。 如何將類別傳遞給孩子,並用 API 調用中的值填充它?

您正在嘗試將異步數據傳遞給子組件。 你有不同的解決方案來做到這一點。 例如,您可以使用ngOnChanges而不是ngOnInit

ngOnChanges() {
    console.log('aaa'+ this.catname);
}

另一種解決方案是使用*ngIf ,以延遲 post 組件的初始化:

<app-room-card *ngIf="categories" [categories]="categories"></app-room-card>

看看這個鏈接: https : //scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components#toc-solution-2-use-ngonchanges

嘗試將您的組件代碼更改為,

export class RoomCardComponent implements OnInit {
   @Input() categories: any; 
   ngOnInit() {
   console.log('aaa'+ this.categories);
   }
}

並且在父組件上有 *ngIf 只是為了確保一旦您從 API 獲得響應,數據就會傳遞給子組件

<app-room-card *ngIf="categories" [categories]="categories"></app-room-card> 

也許你應該以這種方式定義你的輸入,所以當屬性被立即加載時,子組件中會更新:

  @Input('categories')
  set categories(value: any) {
    this._categories = value;
  }

我有同樣的問題,我用布爾類型的變量“加載”修復了;

export class AppComponent {
  title = 'taurs-frontend';
  categories: any;
  isLoggedIn = false;
  loading:boolean = false; -> // my variable

ngOnInit(){
    this.loading = true; -> // true when the request starts 
    this.roomDataService.getData(`${environment.api_url}/api/Categories`)
    .subscribe(categories => {
      this.categories=categories
      this.loading = false; // false with the request ends
    }); 
  }

所以,在 HTML 中

 <app-room-card *ngIf="!loading" [categories]="categories"></app-room-card> 
 // i used this variable to wait data of my parent component 

我希望這可以解決您的問題或幫助其他人。

暫無
暫無

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

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