Part of my code:
import {Injectable} from 'angular2/core';
import {Http, Headers, Request, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class myClass {
constructor(protected http: Http) {}
public myMethod() {
let request = new Request({
method: "GET",
url: "http://my_url"
});
return this.http.request(request)
.map(res => res.json())
.catch(this.handleError); // Trouble line.
// Without this line code works perfectly.
}
public handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
myMethod()
produces exception in console of browser:
ORIGINAL EXCEPTION: TypeError: this.http.request(...).map(...).catch is not a function
Perhaps you can try adding this in your imports:
You can also do:
Per comments:
Similarly, for that, you can use:
The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with
import * as Rx from "rxjs/Rx"
Then make sure to access the
Observable
class asRx.Observable
.New service updated to use the HttpClientModule and RxJS v5.5.x:
Old service, which uses the deprecated HttpModule:
I use
.do()
(now.tap()
) for debugging.When there is a server error, the
body
of theResponse
object I get from the server I'm using (lite-server) contains just text, hence the reason I useerr.text()
above rather thanerr.json().error
. You may need to adjust that line for your server.If
res.json()
raises an error because it could not parse the JSON data,_serverError
will not get aResponse
object, hence the reason for theinstanceof
check.In this plunker, change
url
to./data/data.junk
to generate an error.Users of either service should have code that can handle the error:
in the latest version of angular4 use
it will import all the required things.
There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.
The first method is preferable, the second is a bit outdated, but so far it works too.
1) Solution 1
2) Solution 2. It is old way but still works.