首页 > 解决方案 > 在我调整浏览器大小之前,不会显示在 ngOnInit 中获取的数据

问题描述

我在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,但它没有帮助。

标签: javascriptangulartypescript

解决方案


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

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

推荐阅读