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...