import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'
@Injectable()
export class EquipmentService{
data: any;
constructor(private http:Http){
}
getDefaultEquipment(){
this.http.get('./app/SaveData/equipmentTest.json')
.map((res:Response) => res.json())
.subscribe(data => { this.data = data},
err => console.error(err),
() => console.log(this.data));
}
}
Reading data from a file, The important bit is getDefaultEquipment()
.
If you see the last console.log(this.data) the data is correct, it's exactly what I need. But if I return this.http.get(... () => {return this.data})
i get undefined. How do I get at and return this.data??
Obviously if I write another return such as the following, the observable hasn't completed yet, so it will return the empty data: any.
//clearly won't work because the get hasn't returned yet
getDefaultEquipment(){
this.http.get(...data => {this.data = data}...);
return this.data;
}