【问题标题】:Passing asynchronous value from parent to child component with @Input使用@Input 将异步值从父组件传递到子组件
【发布时间】:2019-06-15 03:53:35
【问题描述】:

我正在尝试以角度 7 传递来自 api、从父组件到子组件的地图。

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 时,它是未定义。如果我尝试从父级导入变量标题,一切正常。如何将类别传递给孩子,并用 API 调用中的值填充它?

【问题讨论】:

  • 您是否尝试过使用 ngIf 仅在解决 API 调用时渲染子组件?否则,您将传递一个未定义的值,直到解决方案发生。您也可以尝试使用不同的生命周期钩子来检测初始化和更改时对值的更改。

标签: angular typescript parent-child angular-components angular7


【解决方案1】:

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

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> 

【讨论】:

  • 相同的结果未定义
  • 你用 ngIF 试过了吗
  • 任何解释为什么这个@Input('categories') catname: any; 不起作用?
  • @MaihanNijat 它会起作用的!只是为了确保 OP 使用没有别名的相同名称
【解决方案2】:

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

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

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

<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

【讨论】:

    【解决方案3】:

    我有同样的问题,我用布尔类型的变量“加载”修复;

    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 
    

    我希望这可以解决您的问题或对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 2016-12-16
      • 2019-01-13
      • 2020-08-25
      • 2020-02-04
      • 2018-06-05
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多