Topics
Published on August 9, 2017 by kudvenkat
Want create site? Find Free WordPress Themes and plugins.

Text version of the video
csharp-video-tutorials.blogspot.com/2017/08/angular-2-http-error-handling.html

Slides
csharp-video-tutorials.blogspot.com/2017/08/angular-2-http-error-handling_9.html

Angular 2 Tutorial playlist

Angular 2 Text articles and slides
csharp-video-tutorials.blogspot.com/2017/06/angular-2-tutorial-for-beginners_12.html

All Dot Net and SQL Server Tutorials in English
www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

All Dot Net and SQL Server Tutorials in Arabic
www.youtube.com/c/KudvenkatArabic/playlists

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.
return this._http.get(‘http://localhost:24535/api/employeess’)
.map((response: Response) =] [IEmployee[]]response.json())
.catch(this.handleError);

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

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.
Since we want the error message color to be red so it stands out, we are using console.error() method instead of console.log() method to log the error 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() {
this._employeeService.getEmployees()
.subscribe(
employeesData =] this.employees = employeesData,
error =] {
console.error(error);
this.statusMessage = ‘Problem with the service. Please try again after sometime’;
});
}

At this point run the application, and notice since we do not have any errors, that data is loaded as expected. Now let’s introduce an error. In employee.component.ts file

Change the url from
localhost:24535/api/employees

To (Notice the extra “s” at the end)
localhost:24535/api/employeess

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”.

To do this in the view template of EmployeeListComponent (employeeList.component.html) bind to statusMessage property of the EmployeeListComponent class as shown below.

[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”

If you comment the following import statement in employee.service.ts, the exception handling still works as expected.
import ‘rxjs/add/Observable/throw’;

However, without the above import statement in employee.service.ts file, if you try to log the error object to the console in ngOnInit() method of EmployeeListComponent the logging does not work as expected.

You will see a message stating – observable_1.observable.throw is not a function, which is not the error message we expected. Angular is complaining that it cannot find throw.

If you uncomment the import statement in employee.service.ts file, then we see the error message we expect.

Did you find apk for android? You can find new Free Android Games and apps.

Leave a Reply

9 Comments on "Angular 2 http error handling"

Notify of
avatar

Hemadri Boddu
Guest
Hemadri Boddu
1 month 9 days ago

Grate tutorial 😋👌👏

Velen
Guest
Velen
2 months 19 days ago

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

Иван Рыбин
Guest
Иван Рыбин
2 months 10 days ago

it maps response.json() to IEmployee[] type

Sajjad Hussain
Guest
Sajjad Hussain
3 months 3 days ago

Waiting for next videos….. Sir….

srikant singh
Guest
srikant singh
3 months 3 days ago

sir when you update next video

Harald Polz
Guest
Harald Polz
3 months 5 days ago
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… Read more »
Harald Polz
Guest
Harald Polz
1 month 29 days ago
I have not deployed anything yet. After all, I am still following your course while building the app I want. And testing a variety of things based on what I learned. But I am using the latest version of VS 2017 (15.3.5) with the spa template and, very important, .Net Core 2.0. It works very well for me. What surprises me most are the differences sometimes between MS Edge and Chrome. And I am using MSSQLLocalDb (SQL Server 13.0.4001.0). I had major problems displaying all data loaded from the server in a table. Some columns refused to display and I… Read more »
rajasekarsj
Guest
rajasekarsj
1 month 29 days ago

Harald Polz I created an angular app using vs 2017 spa template, do you know how to deploy and configure it in IIS on the server. I couldn't find a tutorial for this.

waqar abbas
Guest
waqar abbas
3 months 8 days ago

thump up. (Y)
after this series plx you should continue design pattern series its a very humble request to you .because its a very important series for every developer. I believe most of people agree with this statement. thank you

wpDiscuz