首页 > 解决方案 > .ts 文件中的方法完成后 HTML 类未更新

问题描述

我有以下显示谷歌地图图像的 html 文件。

<div class = 'Pick' >
    <ion-img class='location-image' [src]="selectedLocationImage" > </ion-img>
</div>

在 ngOninit 上,我调用了以下应该更新 selectedLocationImage 字符串的方法。

   latitude: any;
  longitude: any;
  selectedLocationImage: string;
  ngOnInit() {
 this.getlocation(this.deviceinfo.currentdevice).then(response => {this.createPlace(this.latitude, this.longitude); }).catch(err => {});
}

此方法完成后, selectedLocationImage 已成功更新,但我页面上的图像根本不刷新。这种方法确实需要一两秒钟,这就是为什么我认为 HTML 文件中的图像没有更新。我如何设置 html 来持续监控 selectedLocationImage 字符串并相应地更新 ion-inage?

如果我只是在开始时设置一个默认的 selectedLocationImage 它工作正常但是当方法执行它时,它需要几秒钟然后它不会刷新

编辑:这是所要求的 createPlace 方法。

private createPlace(lat: number, lng: number) {
const pickedLocation: DeviceLocation = {
  // tslint:disable-next-line: object-literal-shorthand
  lat: lat,
  // tslint:disable-next-line: object-literal-shorthand
  lng: lng,
  address: null,
  staticMapImageUrl: null
};

this.isLoading = true;
this.getAddress(lat, lng)
  .pipe(
    switchMap(address => {
      pickedLocation.address = address;
      return of(
        this.getMapImage(pickedLocation.lat, pickedLocation.lng, 14)
      );
    })
  )
  .subscribe(staticMapImageUrl => {

    pickedLocation.staticMapImageUrl = staticMapImageUrl;
    this.selectedLocationImage = staticMapImageUrl;
    this.isLoading = false;
    this.locationPick.emit(pickedLocation);
  });
}

标签: htmlangularionic-framework

解决方案


您需要做的就是将*ngIf结构指令放在父 div 上,如下所示:

<div class = 'Pick' *ngIf="selectedLocationImage">
   <ion-img class='location-image' [src]="selectedLocationImage" > </ion-img>
</div>

这样除非有值,否则带有图像的整个父级不会呈现。

发生的事情是您尝试映射undefined到图像的 src,并且如果字段更新,它不会更新。


推荐阅读