代码之家  ›  专栏  ›  技术社区  ›  Rahmat Siswanto

角度6样式背景图像返回空值未更新

  •  0
  • Rahmat Siswanto  · 技术社区  · 6 年前

    我在搜索如何使用[ngStyle][style.backgroundImage背景图片]但是当我在我的项目中实现时,值返回null

    http://localhost:4200/null 404(未找到)

    我的代码是这样的

    getMyStyles(img) {
        const myStyles = {
          'background-image': 'url(\'' + img + '\')'
        };
        return myStyles;
      }
    
      ngOnInit() {
        this.loading = true;
        this.pesertaService.getImage(this.idHasilSimulasi, this.idPaket)
          .then((response) => {
    this.img = response.img;
    })
    }
    

    和我的html

    <div [ngStyle]="getMyStyles(img)" [style.backgroundSize]="'cover'" [style.height.px]="300"> </div>
    

    我也有这个

    [style.backgroundImage]="'url('+ img +')'"
    

    我该怎么办?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Mihir Dave    6 年前

    这是我的想法,

    当您的组件呈现时,它调用ngOnInit(),但由于getImage的异步行为,它将结束,并且getMyStyles()将从HTML调用,此时图像可能尚未到达,并且

    this.img = response.img;
    

    可能没有被处决,

    另一个例子可能是 response.img 本身为空或不是有效的URL

    推荐文章