2

Within the method itself Shows the value, but outside it shows undefined message

Ubigeo.service.ts

 lisProvinciaByDepartamento( ubigeoId: string): Observable<Ubigeo[]> {
    let ubigeo$ = this.http
    .get(`${this.baseUrl}/provincia/${ubigeoId}`, {headers: this.getHeaders()})
    .map(mapUbigeos)
    .catch(handleError);
    return ubigeo$;
}

Detail.component.ts

cargaPronvicia(ubigeoId: string) {
    this._ubigeoService
        .lisProvinciaByDepartamento(ubigeoId)
        .subscribe((p) => {
            this.provinciaSeleccionada = p
                .find(item =>
                    item.ubigeoId.substr(2, 2) === ubigeoId.substr(2, 2));
            this.provincias = p;
            console.log(this.provinciaSeleccionada); //2
        });

    console.log(this.provinciaSeleccionada); //1
}

undefined in console

Isako
  • 35
  • 8
  • It's because your variable is an observable so there isn't a value inside of `this.provinciaSeleccionada` when you log it the first time – Gab Mar 06 '17 at 22:20
  • You should avoid mixing promises and observables because that would defeat the purpose of observables. See @Aravind 's answer – Gab Mar 06 '17 at 22:33
  • @Aravind Meant to but forgot, sorry. Upvoted – Gab Mar 06 '17 at 22:44
  • 1
    Cool. @GabrieleB-David happy coding :) – Aravind Mar 06 '17 at 22:44

1 Answers1

3

Its because the data retrieval is relatively async when you are using it as observalbes. So never use the variable directly,

Good practices

  1. Skip subscription if it is empty.

    cargaPronvicia(ubigeoId: string) {
       this._ubigeoService
        .lisProvinciaByDepartamento(ubigeoId)
         ////////////////////////////////////////////////////////////////
        .skipWhile((p) => p === undefined)
         ////////////////////////////////////////////////////////////////
        .subscribe((p) => {
            this.provinciaSeleccionada = p
                .find(item =>
                    item.ubigeoId.substr(2, 2) === ubigeoId.substr(2, 2));
            this.provincias = p;
            console.log(this.provinciaSeleccionada); //2
        });
    
    console.log(this.provinciaSeleccionada); //1
    }
    
  2. Where ever you are using the subscribed variables, check if it contains data, an example in your case would be

    if(this.provinciaSeleccionada){
        console.log(this.provinciaSeleccionada);
    }
    

Update 1:

  • Use promises with most care, reason is when you are using promises in constructor, your component will not load until the promise is resolved.
    • By this speed of the application will be as expected.
    • Angular2's reactive nature is not utilized.
Aravind
  • 40,391
  • 16
  • 91
  • 110