Angular 2+错误TypeError:无法读取未定义的属性“”

时间:2018-06-22 07:58:24

标签: angular typescript

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

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

其Angular 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 :(得分:0)

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