Angular2 - http.get not calling the webpi

2019-07-07 06:52发布

问题:

I don't know why this command runs properly but I can't find any log of calls in Fiddler...

let z = this.http.get('http://localhost:51158/api/User/TestIT?idUser=0')

The code pass into this step but If I try to catch all the http request using fiddler, I can't find any call...

Do you have idea on what is happening ?

Thanks

回答1:

To initiate a request and receive a response you can add map() and .catch() to return an Observable response from your method.

Example Service:

import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
...

getMyData(): Observable<any> {
    return this.http.get('http://localhost:51158/api/User/TestIT?idUser=0')
        .map((res: Response) => {
           console.log(res); 
           return res;
         })
         .catch((err) => { 
            // TODO: Error handling
            console.log(err); 
            return err;
     }
}

Then subscribe to the Observable-returning method to execute the request:

Example Subscription

...

this.getMyData()
        .subscribe((res: any) => {
            console.log(res);
        },
        error => {
            // TODO: Error handling
            console.log(error);
        });

For a good starter example you can refer to the Angular Tour of Heroes Example

Note: Untested code