javascript - 隐式上下文未定义, Angular 7

标签 javascript angular angular-components

是的,所以我正在遍历一组信息,并且信息以我想要的方式显示,但是,我的控制台中出现了一些看起来很糟糕的错误:ERROR TypeError: "_v.context .$implicit 未定义”

接口(interface)服务:

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>

最后是我的控制台的图像: enter image description here

谢谢你的帮助!

编辑:使标题更具体。

最佳答案

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

如果您通过使用以下符号在某个位置放置一个值来创建数组,就会发生这种情况:

myArray[1] = myObject;

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

使用起来更安全:

myArray.push(myObject);

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

关于javascript - 隐式上下文未定义, Angular 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54793202/

相关文章:

javascript - 在 asp.net 中回发后如何隐藏切换 div

javascript - 两个人可以同时处理同一个 javascript 项目吗?

javascript - Angular 2 什么时候在组件上调用 onDestroy?

angular - 使用带有 resolveComponentFactory 的通用组件会导致 Component<{}> 而不是 <T>

Angular Material : 'mat-dialog-content' is not a known element

javascript - JS倒计时器-暂停功能

javascript - 如果存在另一个类,则更改类

angular - Angular 5 中使用 rxjs 进行持久订阅

Angular 库包依赖

Angular - 如何为可选输入属性设置默认值