简体   繁体   English

Typescript将JSON对象转换为Typescript类

[英]Typescript converting a JSON object to Typescript class

Hello I am attempting to change an array of JSON objects to a TypeScript class. 您好,我正在尝试将JSON对象数组更改为TypeScript类。 However the method seems to crash every I attempt to assign a Json object attribute to a typescript attribute. 但是,该方法似乎在我每次尝试将Json对象属性分配给typescript属性时崩溃。

Typescript interface 打字稿界面

export interface marker {
    lat: number;
    lng: number;
}

Typescript method 打字稿方法

public markers: marker[];

ngOnInit() {
    this.mapService.GetPhotosById(this.id).subscribe(resultlisting => {
        this.values = resultlisting;
        console.log(this.values); //SHOW IN PICTURE
        this.ChangetoMarkers(this.values);
    }, error => this.errorMessage = error);
}

ChangetoMarkers(someArray: Observable<any[]>) {

    for (let entry of someArray) {
        let mark: marker;
        mark.lat = Number(entry.latitude); //Attempt to convert to number
        mark.lng = +entry.longitude; //2nd attempt to convert to number
        this.markers.push(mark);
    };
    console.log(this.markers); //DOES NOT REACH THIS
}

Map Service 地图服务

GetPhotosById(id: string): Observable<any> {
    return this.http
        .post(this.config.apiEndpoint + "mapPhotos/" + id)
        .map(this.extractJson).catch(this.handleErrors);

};
private extractJson(res: Response) {
    let data = res.json();
    return data;
}
private handleErrors(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.log(errMsg);
    return Observable.throw(errMsg);
}

I have researched the issue and have attempted to apply the interger cast but it does not seem to work. 我已经研究了这个问题,并尝试应用interger强制转换,但是它似乎不起作用。 Any suggestions would be great. 任何建议都很好。

As Mauricio Poppe noted in his comment, you are trying to access the properties of a variable that has no value. 正如Mauricio Poppe在评论中指出的那样,您正在尝试访问没有价值的变量的属性。

changeToMarkers(points: Array<{latitude: number, longitude: number}>) {
  this.markers = entries.map(({latitude: lat, longitude: lng}) => ({
    lat,
    lng
  }));

  console.log(this.markers);
}

No number conversions are necessary because the deserialized representations of latitude and longitude are already compatible numeric values. 不需要数字转换,因为经度和纬度的反序列化表示形式已经是兼容的数值。

Try this: 尝试这个:

ChangetoMarkers(someArray: any[]) {
    console.log("array",someArray);
    for (let entry of someArray) {
        let mark: marker = {lat: entry.latitude, lng: entry.longitude};
        console.log("mark", mark);
        this.markers.push(mark);
    };
    console.log("markers",this.markers); 
}

It isn't as elegant as Aluan Haddad's, but it should allow you to determine at which point it is breaking if for some reason this still doesn't work, by logging someArray before the loop, the marks before being pushed, and this.markers after to determine exactly where the problem is breaking down. 它不像Aluan Haddad的那样优雅,但是它应该允许您通过在循环之前记录someArray,在压入之前的标记等等来确定它在哪一点由于某种原因仍然不起作用而中断。之后再使用标记来确定问题所在的确切位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM