1

Good evening to all.

I have an issue when retrieving data from my service to which I have subscribed through subcribe; I get data inside the subscribe function but outside it is UNDEFINED;

Here is the code.

userservice.ts

import { Injectable } from "@angular/core";
import { Http, Response, Headers } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs";

@Injectable()
export class UserService{
  constructor(private http: Http){

  }

getRegistrations(): Observable<any> {
    return this.http.get('http://127.0.0.1:8000/api/candidatesL')
      .map(
        (response: Response) => {
          return response.json().candidates;
        }
      );
  }

  }

all-registration.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from "@angular/forms";
import { Candidate } from "../candidate.interface";
import { Response } from "@angular/http";
import { UserService } from "../user.service";

@Component({
  selector: 'app-all-registration',
  templateUrl: './all-registration.component.html',
  styleUrls: ['./all-registration.component.css']
})
export class AllRegistrationComponent implements OnInit {

  candidates: Candidate[];

  constructor(private userService: UserService) {}

  ngOnInit() {

                this.getRegistration()
                console.log(this.candidates);
             }


    getRegistration(){
    this.userService.getRegistrations()
      .subscribe(
                  (candidates: Candidate[]) => this.candidates = candidates,
                  (error: Response) =>  console.log(error),
                )
  }

    }

When I am inside the .subscribe( ... ) I can display the data but outside I get UNDEFINED.

Please I waiting for your answer...

scg gerard
  • 43
  • 7

2 Answers2

0

since it's an async call, you won't be getting the results right after the call in your ngOnInit(). put console statement in your subscribe call and then you will see the candidates

    getRegistration(){
        this.userService.getRegistrations()
          .subscribe(
                      (candidates: Candidate[]) => {
            this.candidates = candidates
            console.log(this.candidates);
             },
                      (error: Response) =>  console.log(error),
                    )
      }

Update you have already defined candidates as property on your class, so you can display its value in your html like:

<div>{{candidates}}<div>

or if its a json

<div *ngIf="candidates">{{candidates | json}}<div>

as soon as you assign the value in subscribe, it will display whatever the value is. If you want to check to display the value only when it has a value ( after the subscribe completes) you can always put a *ngIf directive to check the value on the html element.

JayDeeEss
  • 1,075
  • 9
  • 14
0

Your code is working perfectly fine and that is the normal behavior of Observable type variable.

ngOnInit() {

  this.getRegistration()  // this will set the value of this.candidates in future as its async.
  console.log(this.candidates); // this line will executed immediately before the observable returns a value.
}

So your console.log gave you undefined. Its always good advice to handle the values inside observables.

ngOnInit() {

  this.userService.getRegistrations().subscribe((candidates: Candidate[]) => {
      this.candidates = candidates;
      console.log(this.candidates);
    },
        (error: Response) =>  console.log(error)
    );
}

As your service is returning a observable, A value can be extracted from it only subscribing it. Remember its not the direct variable but a observable<any> variable.

Aniruddha Das
  • 20,520
  • 23
  • 96
  • 132