I'm testing angular2 and trying to retrieve data from a restful service.
My service is like this:
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {annuaireModel} from '../../models/annuaireModel';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class annuaireService {
constructor(private _http: Http) { };
getAnnuaire( codeRne : string) {
var url = 'http://192.168.40.30/api/editionsstandardsAPI/lireannuaire?codeEtablissement=' + codeRne ;
return this._http.get(url).map(res => <annuaireModel>res.json()).catch(this.gestErreur);
}
gestErreur(error: Response ) {
console.error(error);
return Observable.throw(error.json() || 'Erreur serveur');
}
/*getHero(id: number) {
return Promise.resolve(HEROES).then(heroes => heroes.filter(hero => hero.id === id)[0]);
}*/
}
My Component :
import {Component} from '@angular/core';
import {HTTP_PROVIDERS} from '@angular/http';
import {annuaireService} from './annuaireService';
import {annuaireModel} from '../../models/annuaireModel';
@Component({
templateUrl: 'app/editionsStandards/annuaire/annuaire.html',
selector: 'annuaire',
directives: [],
providers: [HTTP_PROVIDERS,annuaireService]
})
export class annuaireComponent {
annuaire : annuaireModel;
variableTest : string;
constructor( private _annuaireService :annuaireService) { }
ngOnInit() {
}
chargerAnnuaire() {
this._annuaireService.getAnnuaire('7508987231').subscribe(
data =>
{this.annuaire = data} ,
error => alert(error),
() => console.log('OK')
);
}
}
My html :
<h1>Annuaire</h1>
<button (click)="chargerAnnuaire()" type="button">test</button>
<div >
{{annuaire.entete.raisonSociale}}
</div>
When I launch the website , I have this error :
cannot read the property entente of undefined.
I've tested my restful service and it does return goo json ....
Help ! I can't figure what I'm doing wrong. Thanks
Try Elvis
operator ?.
{{ annuaire?.entete.raisonSociale }}
In case annuaire
is falsy
(undefined, null, etc.) it won't access entete
member.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.