I am currently working on retrieving data from a RESTful web service using Angular 2 Http.
Initially, I inject the service into the constructor of the client component class:
constructor (private _myService: MyService,
private route: ActivatedRoute,
private router: Router) {}
To fetch data from the web service, I have added a getData() method that calls a function of MyService:
getData(myArg: string) {
this._myService.fetchData(myArg)
.subscribe(data => this.jsonData = JSON.stringify(data),
error => alert(error),
() => console.log("Finished")
);
console.log('response ' + this.jsonData);
In the ngOnInit method of the client component class, I invoke the getData() method (ensuring proper import and implementation of the OnInit interface):
this.getData(this.myArg);
Below is the code for the MyService service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MyService {
constructor (private _http: Http) {}
fetchData(myArg: string) {
return this._http.get("http://date.jsontest.com/").map(res => res.json());
}
}
However, I am facing difficulty in fetching the data. When I attempt to test it using
console.log('response ' + this.jsonData);
in the getData() method above, the browser displays response undefined
.
Note: The attribute jsonData is a string type within the client component class.