Converter JSON para Objecto TypeScript (Angular 2)

Pessoal, bom dia.

Estou quebrando a cabeça por alguns dias e finalmente resolvi perguntar para vocês.

Estou desenvolvendo uma aplicação em Angular 2, buscando as informações individualizadas via REST e está funcionando. Afim de reduzir as chamadas para o servidor backend, decidi ir buscar somente uma vez no servidor as informações que eu preciso para montar as informações na tela. Ao fazer isso o REST está devolvendo o resultado certo, porém eu não estou conseguindo importar os objetos do JSON retornado.

Segue abaixo dois objetos que eu tenho e onde estou parado.

//month.ts
export class Month {
  constructor(
    public id: string,
    public number: number,
    public name: string) {}
}

// weather.ts
export class Weather {
  constructor(
    public id: string,
    public name: string,
    public min: number,
    public max: number
  ) {}
}

//month.service -> isso funciona
public getMonthsByIsoName = (): Observable<Month[]> => {

      return this._http.get(this.actionUrl + '/list/en')
        .map((res: Response) => { this.months = res.json(); return this.months; })
        .catch(this.handleError);
  }

//plan.service
public getPlanAddCityInformationPageObjects = (): Observable<PlanAddCityInformation> => {
      return (this._http.get(this.actionUrl + '/list/en')
        .map((res: Response) => {
        // eh aqui que preciso converter para os objetos month e weather
        }));
      
    }

Mande o GITHUB do seu projeto para eu da uma olhada !

import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http';

import { Observable } from ‘rxjs/Observable’;
import ‘rxjs/add/operator/map’;
import ‘rxjs/add/operator/catch’;
import ‘rxjs/add/observable/throw’;

//import {LeitoresService} from ‘…/shared/leitores.service’;
import {Leitor} from ‘…/shared/leitor’;

@Injectable()
export class LeitorSearchService {
constructor(private http: Http) { }

search(term: string): Observable<Leitor[]> {
return this.http
.get(http://172.29.0.30:8087/pontows/webresources/relogio/${term})
.map((r: Response) => r.json().data as Leitor[])
.catch((error: any) => {
console.error(’======================= NÃO ENCONTRADO==============’+ term);
return Observable.throw(error.message || error);
});
}
}

Obrigado pela ajuda, mas quais são os atributos do leitor?

Att

Nilson

Olá, não sei como está vindo o retorno do seu back. Mas vou deduzir:


class CityInformation {
    public weather: Weather;
    public month: Month;
    constructor(weather: Weather, month: Month) { 
        this.weather = weather;
        this.month = month;
    }
}
public getPlanAddCityInformationPageObjects = (): Observable<PlanAddCityInformation> => {
      return this._http.get(this.actionUrl + '/list/en')
                 .map((res: Response) => res.json().data as CityInformation);
    }

Qualquer duvida, comente.
[]'s

O rest está retornando isso

{ "months": [ { "id": "5871b7eeac8a24322f92c0d0", "number": 1, "name": "Janeiro" }, { "id": "5871b80fac8a24322f92c0e9", "number": 2, "name": "Fevereiro" }, { "id": "5871b820ac8a24322f92c0f0", "number": 3, "name": "MarÁo" }, { "id": "5871b82bac8a24322f92c0f7", "number": 4, "name": "Abril" }, { "id": "5871b839ac8a24322f92c100", "number": 5, "name": "Maio" }, { "id": "5871b855ac8a24322f92c109", "number": 6, "name": "Junho" }, { "id": "5871b863ac8a24322f92c110", "number": 7, "name": "Julho" }, { "id": "5871b872ac8a24322f92c119", "number": 8, "name": "Agosto" }, { "id": "5871b883ac8a24322f92c122", "number": 9, "name": "Setembro" }, { "id": "5871b893ac8a24322f92c127", "number": 10, "name": "Outubro" }, { "id": "5871b8aeac8a24322f92c135", "number": 11, "name": "Novembro" }, { "id": "5871b8c4ac8a24322f92c13e", "number": 11, "name": "Dezembro" } ] }, { "weathers": [ { "id": "58741d0cac8a24322f92ca44", "name": "Muito Quente", "min": 30.0, "max": 99.0, "translations": null }, { "id": "58741d97ac8a24322f92ca4e", "name": "Quente", "min": 20.0, "max": 29.9, "translations": null }, { "id": "58741ddeac8a24322f92ca57", "name": "Frio", "min": 0.0, "max": 19.9, "translations": null }, { "id": "58741e02ac8a24322f92ca5b", "name": "Muito Frio", "min": -99.0, "max": 0.0, "translations": null }, { "id": "58741eb0ac8a24322f92ca76", "name": "Chuvoso", "min": null, "max": null, "translations": null }, { "id": "58741ef0ac8a24322f92ca7e", "name": "Neve", "min": null, "max": null, "translations": null } ] }

1 curtida

Ahh entendi. É uma lista com as diversas opções. Ok, vê se essa funciona.

class CityInformation { //nomeie isso com algo mais coerente com a tua aplicação.
    public weathers: Weather[];
    public months: Month[];
    constructor(weathers: Weather[], months: Months) { 
        this.weathers = weathers;
        this.months = months;
    }
}
public getPlanAddCityInformationPageObjects = (): Observable<PlanAddCityInformation> => {
      return this._http.get(this.actionUrl + '/list/en')
                 .map((res: Response) => res.json().data as CityInformation);
    }

Então quer aprender Angular 2?
Pega aqui um cupom de desconto para fazer o seu curso na Udemy. Para recebê-lo, você só tem de se inscrever na lista

http://eepurl.com/cA23Ff

Além de receber este cupom de desconto, você irá receber cupons para outros cursos relacionados ao desenvolvimento de software.