首页 文章

Angular 2 ERROR TypeError:无法读取未定义的属性'''[duplicate]

提问于
浏览
0

这个问题在这里已有答案:

我在这里看到了同样的问题,但我尝试了一些解决方案,但我无法解决这个问题 .

我从JSON文件接收数据并使用服务打印出值 . 问题是我可以在控制台中看到错误,例如“ERROR TypeError:无法读取未定义的属性'0'” .

它的角度2 .

请参阅以下代码:

iberpagetop.component.ts

export class IberPageTopComponent implements OnInit {
location: any[];  

constructor(private _locationService: LocationService, private translate: TranslateService) {
    translate.setDefaultLang('en'); 
}

switchLanguage(language: string) {
     this.translate.use(language);
}

ngOnInit() {
    this._locationService.getLocationData()
        .subscribe(data => this.location = data)

}

IberpageTop.html

<table class="">            
        <tbody>
        <tr>
          <td><h3>DOÑA BENITA</h3></td>
          <td> <p><span translate>Business</span> {{ location[0].bussines }}</p></td>
          <td><p><span translate>Sub-Region</span> {{ location[0].subRegion }}</p></td>
        </tr>
        <tr>
          <td><p><span translate>Power</span> {{ location[0].power }}</p></td>              
          <td><p><span translate>Country</span> {{ location[0].country }}</p></td>
          <td><p><span translate>Maint. Region</span> {{ location[0].maintRegion }}</p></td>
        </tr>
        <tr>

          <td><p><span translate>Last updated</span> {{ location[0].lastUpdate }}</p></td>
          <td><p><span translate>Region</span> {{ location[0].region }}</p></td>
          <td><p><span translate>Main Area</span> {{ location[0].mainArea }}</p></td>
        </tr>
        </tbody>
    </table>

locations.json

[{
    "field": "DOÑA BENITA",
    "power": "32MW",
    "lastUpdate": "03/12/2018",
    "bussines": "ESP",
    "country": "SPAIN",
    "region": "ANDALUCIA",
    "subRegion": "CÁDIZ",
    "maintRegion": "SUR",
    "mainArea": "CÁDIZ"
}]

locations.ts(界面)

export interface ILocation {
    field: string,
    power: string,
    lastUpdate: Date,
    bussines: string,
    country: string,
    region: string,
    subRegion: string,
    maintRegion: string,
    mainArea: string
}

location.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ILocation } from '../location';
import { Observable } from 'rxjs';


@Injectable()
export class LocationService {

    private _url: string = "/assets/data/locations.json";


    constructor(private http: HttpClient) {}

    getLocationData(): Observable<ILocation[]> {
        return this.http.get<ILocation[]>(this._url);
    }
}

我会感激任何帮助 . 提前致谢 .

1 回答

  • 0

    你应该用它来处理这种错误 . 在所有情况下,您使用此 location[0]?.<YOUR_KEY> 而不是 location[0].<YOUR_KEY> 来处理html页面中的错误 .

相关问题