首页 > 解决方案 > 隐式上下文未定义,角度 7

问题描述

是的,所以我正在迭代一系列信息,并且信息显示了我想要的方式,但是,我在控制台中遇到了一些看起来很奇怪的错误:ERROR TypeError: "_v.context.$implicit is undefined"

api服务:

private extractData(res: Response) {
    let body = res;
    return body || {};
  }

  getWeather(city: string, isoCode: string): Observable<any> {
    return this.http.get(`${this.endPoint}${city},${isoCode}${this.constants.apiKey}`)
    .pipe(map(this.extractData));
  }

使用 api 服务的组件:

  theWeather:any = [];
  countryList = COUNTRIES;
  isLoading: boolean = true;
  showWeather: boolean = false;

  constructor(private apiCall:ApiService) { }


  ngOnInit() {
    this.retrieveWeather()
  };

  retrieveWeather() {
    console.log('COUNTRY LIST', this.countryList);

    this.theWeather = [];
    this.countryList.map((element, i) => {
      this.apiCall.getWeather(element.city, element.countryIso)
        .subscribe((data: {}) => {
          element.weatherInfo = data;
        });
        this.isLoading = false;
      });
      this.showWeather = true;
  };

和html文件:

<div class="country-container">
  <div *ngIf="isLoading">
    <mat-card>
      <mat-progress-spinner class="spinner-style" color="primary" mode="indeterminate"></mat-progress-spinner>
    </mat-card>
  </div>
  <div *ngIf="showWeather" class="card-container">
    <mat-card *ngFor="let c of countryList" class="card">
      <mat-card-title>Weather for: {{c.city}}, {{c.countryName}}</mat-card-title>
      <mat-card-content>The current weather is: {{c.weatherInfo.weather[0].description}}</mat-card-content>
    </mat-card>

  </div>
</div>

最后是我的控制台的图像: 在此处输入图像描述

感谢您的帮助!

编辑:使标题更具体地针对问题。

标签: javascriptangularangular-components

解决方案


当角度模板循环遍历一组项目,并且一个或多个数组元素未定义时,您会收到此错误。

如果您通过使用以下表示法将值放置在某个位置来创建数组,则可能会发生这种情况:

myArray[1] = myObject;

如果你这样做,那么 myArray[0] 将没有值,并且当 angular 循环通过它时,你会得到错误“_v.context.$implicit is undefined”。

使用更安全:

myArray.push(myObject);

如果您从数组中删除一个元素,在索引处留下一个未定义的值,您也可能会得到这个。


推荐阅读