我正在测试angular2并试图从一个宁静的服务中检索数据。
我的服务是这样的:
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]);
}*/
}
我的组件:
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')
);
}
}
我的HTML:
<h1>Annuaire</h1>
<button (click)="chargerAnnuaire()" type="button">test</button>
<div >
{{annuaire.entete.raisonSociale}}
</div>
当我启动网站时,出现此错误:
cannot read the property entente of undefined.
我已经测试了我的休息服务,它确实返回了goo json ....
帮助!我无法弄清楚我做错了什么。谢谢
答案 0 :(得分:2)
尝试Elvis
运算符?.
{{ annuaire?.entete.raisonSociale }}
如果annuaire
为falsy
(未定义,为空等),则无法访问entete
成员。