使用@Input 将异步值从 parent 传递到 child 组件

Passing asynchronous value from parent to child component with @Input

我正在尝试传递来自 api 的地图,从 parent 到 child 组件,在 angular 7.

parent.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
    }); 
  }

parent.html:

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

child.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。如果我尝试从 parent 导入变量标题,一切正常。如何将类别传递给 child,并用 API 调用中的值填充它?

尝试将您的组件代码更改为,

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> 

您正试图将异步数据传递给子组件。你有不同的解决方案来做到这一点。例如,您可以使用 ngOnChanges 而不是 ngOnInit:

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

另一种解决方案是使用*ngIf,以延迟帖子组件的初始化:

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

看看这个link:https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components#toc-solution-2-use-ngonchanges

我遇到了同样的问题,我用布尔类型的变量“loading”修复了问题;

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 

我希望这能解决您的问题或帮助其他人。