1

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

1 Answer 1

2

Try Elvis operator ?.

{{ annuaire?.entete.raisonSociale }}

In case annuaire is falsy (undefined, null, etc.) it won't access entete member.

Sign up to request clarification or add additional context in comments.

2 Comments

You may also need the Elvis operator for entete as well.
you're absolutly right !! I wrote this : {{annuaire?.entete?.raisonSociale}} and it works fine. i've already tried the elvis operator but on the first element only not the second too. many many thanks andrei

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.