隐式上下文未定义,角度 7

Ctf*_*cia 4 javascript angular-components angular

是的,所以我正在迭代一系列信息,并且这些信息按照我想要的方式显示,但是,我在控制台中收到了一些令人惊讶的错误: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));
  }
Run Code Online (Sandbox Code Playgroud)

使用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;
  };
Run Code Online (Sandbox Code Playgroud)

和 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>
Run Code Online (Sandbox Code Playgroud)

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

感谢您的帮助!

编辑:使标题更具体地解决问题。

小智 5

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

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

myArray[1] = myObject;
Run Code Online (Sandbox Code Playgroud)

如果这样做,那么 myArray[0] 将没有值,并且当 Angular 循环遍历它时,您将收到错误“_v.context.$implicit is undefined”。

使用更安全:

myArray.push(myObject);
Run Code Online (Sandbox Code Playgroud)

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