Christophe
Christophe

Reputation: 33

How to correctly parse JSON response

I'm trying to parse rest resquest to my angular2 component, but it doesn't work. How do I parse correctly json to put it in my html template?

My code :

myService :

@Injectable()
export class ExchangeConfigurationService {
    getTransports() : Observable<Transport[]>{
        const header = new Headers();
        header.append('Accept', 'application/json');
        return this._http.get('http://localhost:8090/1.0/transports', {headers: header}).map(response => (response.json() as Transport[]));
    }
}

myInterface :

export interface Transport {
    id                 : number,
    nom                : string,
    description        : string,
    type               : string,
    configuration    : Configuration[],
}

myComponent :

@Component(
{
    selector: 'exchange-palette',
    styleUrls : ['app/components/exchange/exchange.component.css'],
    templateUrl:'/app/components/exchange-palette/exchange-palette.component.html',
    providers : [ExchangeConfigurationService],
})
export class ExchangePaletteComponent implements OnInit{
    transports : Transport[] = [];

    constructor(private _exchangeConfigurationService : ExchangeConfigurationService){}

    ngOnInit() {
        this._exchangeConfigurationService.getTransports().subscribe(data => this.transports = data,
                                                                    error => console.error(error));
    }
}

**My html code: ** {{transport.type}}

Rest service response :

{"transports":{
    "transport":[
        {
            "id":1,
            "nom":"FTP Client",
            "description":"Connexion à un serveur FTP client",
            "type":"FTP",
            "configuration":[
                {
                    "cle":"ftp.hote",
                    "obligatoire":true
                },
                {
                    "cle":"ftp.identifiant",
                    "obligatoire":true
                },
            ]
        },
        {
            "id":2,
            "nom":"Google Drive",
            "description":"Connexion à un google drive",
            "type":"GOOGLE_DRIVE"
        }
    }
}

It seems that my json is not correctly map to my transports var. Have an idea?

Thans.

Upvotes: 0

Views: 155

Answers (1)

Sasxa
Sasxa

Reputation: 41314

Try this:

getTransports() : Observable<Transport[]>{
    const header = new Headers();
    header.append('Accept', 'application/json');
    return this
      ._http.get('http://localhost:8090/1.0/transports', {headers: header})
      .map(response => response.json())
      .map(transports => (transports.transport as Transport[]))
}

Upvotes: 1

Related Questions