I do error handler code, but I got error in catch. undefined method.
This is my serivce.ts code.
import { Injectable } from "@angular/core";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { user } from "./user";
import { Observable } from "rxjs";
import "rxjs/add/operator/catch";
import "rxjs/add/Observable/throw";
@Injectable({
providedIn: "root"
})
export class DemoService {
private url: string = "/assets/demo/user.json";
constructor(private http: HttpClient) {}
getuserdetails(): Observable<user[]> {
return this.http.get<user[]>(this.url).catch(this.errorHandler);
}
errorHandler(error: HttpErrorResponse) {
return Observable.throw(error.message || "server error.");
}
}
This is my app.component.ts file code
public userdetails = [];
public errorMsg;
constructor(private user: DemoService) {}
ngOnInit() {
this.user
.getuserdetails()
.subscribe(
$data => (this.userdetails = $data),
error => (this.errorMsg = error)
);
}
I got error in catch. and error message is Property 'catch' does not exist on type 'Observable'.
You can use catchError
in rxjs/operators
for this.
Try it as follows.
import { catchError } from 'rxjs/operators';
export class DemoService {
getuserdetails(): Observable<user[]> {
return this.http.get<user[]>(this.url)
.pipe(catchError(this.errorHandler))
}
errorHandler(error: HttpErrorResponse) {
return Observable.throw(error.message || "server error.");
}
}