Angular 2 http error handling

preview_player
Показать описание
Text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

Slides

Angular 2 Tutorial playlist

Angular 2 Text articles and slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

Tags
angular 2 observable throw is not a function
angular 2 observable throw error
angular 2 observable catch error

In this video we will discuss error handling in Angular.

When using http, to call a web service, errors may occur. When they do occur we want to handle these errors.

We use the catch operator to catch any exceptions that occur.
Before we use the catch operator we have to import it, just like how we imported map operator.
import 'rxjs/add/operator/catch';

The catch operator can then be chained to the map operator.

To the catch operator we are passing another method (handleError). This handleError() method is called when there is an exception.
handleError(error: Response) {
}

In a real world application we may pass the error to a loggin service to log the error to a file or a database table, so the developers can see these errors and fix them if required.
In our case, to keep things simple we are logging to the browser console.
After we log the error, we are throwing the error back, so the components that use this service are notified about the error condition, so they can display a meaningful error message to the user.
To use throw, we will have to import it from rxjs
import 'rxjs/add/Observable/throw';

We are calling this service from EmployeeListComponent. So we need to handle the error we have thrown from the service and display a meaningful message to the user. We are subscribing to the service, in ngOnInit() life cycle hook of EmployeeListComponent. Notice there are 2 parameters to the subscribe() function. Both these parameters are arrow functions. The first arrow function is called when the Observable successfully emits an item. The second arrow function is called, when there is an error.

ngOnInit() {
.subscribe(
error =] {
});
}

Change the url from

To (Notice the extra "s" at the end)

At this point when you reload the page in the browser, you will see the message "Loading data. Please wait...", but the data never loads.

Now launch browser developer tools and you will see the error message logged to the console by the service.

This message - "Loading data. Please wait..." is misleading in this case. Instead we should be displaying a meaningful message like - "Problem with the service. Please try again after sometime".

[tr *ngIf="!employees"]
[td colspan="5"]
{{statusMessage}}
[/td]
[/tr]

With the above change, while the service is busy retrieving data, we see the message "Loading data. Please wait..." and if there is an error we see the message "Problem with the service. Please try again after sometime"

import 'rxjs/add/Observable/throw';

Рекомендации по теме
Комментарии
Автор

This is deprecated for Angular versions above 5.
The new implementation of this is the following:

1) Import Observable and catchError like this:
import { catchError } from 'rxjs/operators';
import { Observable } from 'rxjs';

2) After that, catch the exception as in this example
createPosts(post){
return this.http.post(this.url, JSON.stringify(post)).pipe(
catchError((err: Response)=>{
return Observable.throw(err);
})
);
}

SoferPeOZN
Автор

An amazing tutorial. Since i subscribe to kudvenkat channel on youtube i stop buying books on the areas he covers. Some books are full of errors, verbose and not fulfil your requirement. Keep it up.

ebrimasidibeh
Автор

Is there any typescript hero here asking because we are implementing most of the services contain GET, POST, PUT, DELETE methods, each and every file service file contain those service methods, is there any way to use Interfaces for them in typescript?

fkamss
Автор

Very helpfult tutorials. Many thanks for your great efforts :)

mahmoudelsayed
Автор

Your tutorials are excellent!!!
However, you may want to consider updating some of them as they are really, really outdated. Your tutorials are still based on VS 2015 whereas the newest version is VS 2017, and even there is already an updated version available for testing.
Why I am mentioning this? VS 2017 offers many more options, some packages like TypeScript are already included, and the file structure inside the ASP.NET Web application is completely different.
And than there is another option: ASP.NET Core which is supposed to make life easier. Well, I have not found a way to properly integrate Angular 2 (or better yet 4) with an ASP.NET Core based database. For whatever reason this has not been addressed by anybody at all. The currently available template for VS 2017, i.e.
dotnet new --install provides an excellent starting environment but no info on how to integrate the database with Angular 2.

Maybe, just maybe you can address these issues? :-)
Thanks for listening.
Harald

hapzfl
Автор

I am using angular 5,
this error handling does not work with .map in the canActivate method while doing authentication using authGuard. Please help me with this

adnansheikh
Автор

The .catch method gives an error, say it don't exist. I am currently using angular 4.

Johnn
Автор

How to declare array and populating it in home.ts ?

sachinchakravarthys
Автор

Sir, using services how to get data from mysql in angular.

santhoshkumar-sfbc
Автор

so you only display your own vague error message to clients instead of display the actual error message? how is that Error Handle?

terrymeng
Автор

Hey, what does <IEmployee[]>response.json() mean?

velen