【问题标题】:Data fetched in ngOnInit does not display until I resize my browser在我调整浏览器大小之前,不会显示在 ngOnInit 中获取的数据
【发布时间】:2020-05-01 03:12:42
【问题描述】:

我在ngOnInit() 中提取了一些数据用于对话。当对话框最初弹出时,没有显示任何数据。如果我手动调整浏览器窗口的大小,它就会出现。如果我导航到弹出窗口中的不同选项卡,然后返回原始选项卡,数据也会出现。 我的 ngOnInit -

ngOnInit(): void {
  this.route.params.pipe(takeUntil(this.destroy$)).subscribe( res => {
    this.itemId = res.itemId;
    this.getItemComponents(this.itemId);
    console.log(this.itemComponents);
}

页面加载时,console.log 显示未定义。我在 getItemComponents 方法中放置了相同的 console.log,如下所示:-

getItemComponents {
  this.itemService.getComponents.subscribe( res => {
    this.itemComponents = res;
    console.log(this.itemComponents);
}

上面的控制台日志记录了我想要的数据。 有什么办法吗?我曾尝试在我的 HTML 中使用 ngIf,但没有帮助。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    您在ngOnInit 钩子上的console.log 方法在您的getItemComponents 方法订阅完成之前启动,因此您需要将它组合在一个链中。尝试使用类似的东西:

    ngOnInit(): void {
        this.route.params
            .pipe(
                takeUntil(this.destroy$),
                switchMap(res => this.itemService.getComponents(res.itemId))
            )
            .subscribe( data => {
                this.itemComponents = data;
                console.log(this.itemComponents);
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 2012-03-12
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多