javascript - 隐式上下文未定义,角度 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>
感谢您的帮助!
编辑:使标题更具体地针对问题。
解决方案
当角度模板循环遍历一组项目,并且一个或多个数组元素未定义时,您会收到此错误。
如果您通过使用以下表示法将值放置在某个位置来创建数组,则可能会发生这种情况:
myArray[1] = myObject;
如果你这样做,那么 myArray[0] 将没有值,并且当 angular 循环通过它时,你会得到错误“_v.context.$implicit is undefined”。
使用更安全:
myArray.push(myObject);
如果您从数组中删除一个元素,在索引处留下一个未定义的值,您也可能会得到这个。
推荐阅读
- java - Spring Boot Oauth2 Client(Reactive) Mutual TLS/SSL token uri
- php - Dompdf 版本 0.8.5 阿拉伯语 RTL 未正确显示
- assembly - 此代码没有错误,但我仍然没有得到正确的答案
- markdown - 使用 markdown 突出显示代码会生成内联代码块
- go - How to save and retrieve Gorm's many2many relationship using Go
- mvvm - SwiftUI - @Binding 到访问 ObservableObject 属性内的值的计算属性会复制变量吗?
- python - 如何在 Python 中删除与对象具有相同属性的对象?
- sql-server - JPA/Wildfly/MsSql:GenericJDBCException:无法获取 JDBC 连接
- python - 根据 NetworkX 中的权重改变边缘的厚度
- azure-machine-learning-service - 从 Azure ML 连接到现有的 Azure 容器实例 ACI