Fetching data from REST Web Service using Angular

2019-07-15 03:01发布

问题:

I'm trying to fetch data from a REST web service using Angular 2 Http.

I first inject the service in the constructor of the client component class that calls it:

constructor (private _myService: MyService,
             private route: ActivatedRoute,
             private router: Router) {}

I added a getData() method that calls a method of MyService to fetch data from the web service:

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);

I call the getData() method in the ngOnInit method of the client component class (I correctly imported and implemented the OnInit interface):

this.getData(this.myArg);

Here is 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());
        }
    }

I don't manage to fetch the data and when I try to test it using console.log('response ' + this.jsonData); in the getData() method above, I get response undefined in the browser.

PS: jsonData is a string attribute of the client component class.

回答1:

Since http requests are async, this.jsonData won't be set at the time where you try to log it to console. Instead put that log into the subscribe callback:

getData(myArg: string){     
    this._myService.fetchData(myArg)
             .subscribe(data => { 
                            this.jsonData = JSON.stringify(data)
                            console.log(this.jsonData);
                        },
                        error => alert(error),
                        () => console.log("Finished")
    );
}