0

I have a json file containing some data ang using HTTP Get request to get the file.

this is my service.

import 'rxjs/Rx'
import { HTTP } from '@angular/http'
import {Injectable} from '@angular/core'
@Injectable

export class service{
constructor(private http: HTTP){
getDesignation(){
return this.http.get('URL path').map((res: Responce) => res.json());
}
}
}

This is the component where I'm consuming my service.

 import { service } from './service'

export class Compo1{

 public designation; any[] = [];

constructor(private httpService: service){
this.httpService().subscribe((data => {
const myarray = [];
for(let key in data){
myArray.push(data[key]);
}
 this.designation = myArray;
console.log(this.designation) ///// This works I can see data in     console....
});
console.log(this.designation) //// This does not work.....
}
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Rohan Sampat
  • 930
  • 1
  • 13
  • 30
  • it's to do with the use of this. – Katana24 Mar 02 '17 at 10:08
  • This is the way subscribe (and async code) works. The data is only accessible within the subscribe. If you want to use it elsewhere in your class, you need to assign a class property **from within the subscribe** (`this.designation = data`) and you need to wait until the async call has returned. – AngularChef Mar 02 '17 at 10:11
  • Sorry i forgot that line... this.designation = myArray; Not i have updated the code. But with this to it does not work – Rohan Sampat Mar 02 '17 at 10:21

0 Answers0