1573013179
Learn Error handling in Angular 8/9, we will take the best approach with RxJS catchError / catchError operators and HttpInterceptor to handle client-side errors gracefully.
A proper Error handling makes an application most helpful for users from the user experience aspect. Error handlers report a user correctly what causing the problem vise verse. It also notifies developers in the development phase about the error reason, which assists them to fix it before it goes live.
These days new technologies are growing faster than ever. This competition is all about making a piece of software better for users be it a final user, product owner or a developer who is building it from scratch. Due to this, user experiences became the trend.
There are two types of errors which might occur in an application, inside errors and outside errors.
Outside Errors: These errors often occur from the server-side and usually starts with (5xxx) status code. These errors return the error message with the proper reason so identifying these errors is easy.
Inside Error: When something unexpected happens, then these errors are thrown. These errors occur with the proper message, which contains the reason for the error occurrence.
Here is the complete List of HTTP status codes.
Next, we practically understand how to handle client-side errors in Angular. A Client-side error handling is one of the features among other various features for developing a user friendly application.
A user gets frustrated when suddenly an app stopped working, and the user doesn’t find the reason for it. It downgrades the overall user experience of the application. To enhance the user experience, we must properly handle errors.
We will use the regular error handling approaches such as handling errors with RxJS operators catchError and throwError and managing errors with HttpClient and HttpInterceptor.
The simplest way to handle errors in Angular is to use Angular’s HttpClient service along with RxJS operators throwError
and catchError
. Http request is made, and it returns the data with a response if anything wrong happens then it returns an error object with error status code.
Below is the service in which we used the handleError() function to handle errors in Angular.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
class Post {
constructor(
public id: string,
public title: string,
public body: string
) { }
}
@Injectable({
providedIn: 'root'
})
export class PostService {
private endpoint = 'https://jsonplaceholder.typicode.com/xyz';
constructor(private http: HttpClient) { }
getPost(): Observable<Post[]> {
return this.http.get<Post[]>(this.endpoint)
.pipe(
retry(1),
catchError(this.handleError)
);
}
handleError(error) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
}
In the service, we defined the handleError()
method. In this method, we are checking if the error is an instance of ErrorEvent
. This function returns either the client-side or server-side error. This error is useful for a single service. Still, when it comes to managing multiple services, then we have to update the handleError function in every service even for a minor change.
To handle errors properly HttpInterceptor is the best way, It intercepts Http request. It helps in converting http request before sending and after getting the response from the server. It is better used for updating data format, setting up headers, adding auth tokens etc. HttpInterceptor service offers better way to systematically handle errors in an Angular app.
The following ErrorIntercept service can manage multiple services. We are using retry(1) and catchError RxJS operators to check the HttpErrorResponse. This code is centralised in nature and can be managed from one place by far this has been the best way to manage errors in Angular.
Add the following code in error.interceptor.ts
:
import {
HttpEvent,
HttpHandler,
HttpRequest,
HttpErrorResponse,
HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
export class ErrorIntercept implements HttpInterceptor {
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Status: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
})
)
}
}
Import HttpClientmodule, HTTP_INTERCEPTORS and ErrorIntercept in app.module.ts
, next inject the HTTP_INTERCEPTORS and ErrorIntercept in providers array along with that set multi: true.
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorIntercept } from './error.interceptor';
@NgModule({
declarations: [...],
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorIntercept,
multi: true
}
],
bootstrap: [...]
})
export class AppModule { }
Here is the post.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
class Post {
constructor(
public id: string,
public title: string,
public body: string
) { }
}
@Injectable({
providedIn: 'root'
})
export class PostService {
private endpoint = 'https://jsonplaceholder.typicode.com/xyz';
constructor(private http: HttpClient) { }
getPost(): Observable<Post[]> {
return this.http.get<Post[]>(this.endpoint)
}
}
Finally we have completed error handling tutorial with examples, I hope this tutorial help you to understand the basic concept of handling client-side errors in Angular 8/9 with RxJS operators and HttpInterceptor.
#angular #web-development
1598940617
Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.
In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!
For Installing Angular on your Machine, there are 2 prerequisites:
First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js
Download and Install Node.js version suitable for your machine’s operating system.
Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
1626834660
In this video, we will see how to improve our code using the #rxs map operator and #angular #async pipe.
The components should be clean and minimal and should not have code that manipulates the data. Responsible for data manipulation is a service.
The goal is to prepare our data and return an #observable pipe so that we can use an #async pipe in the template.
code: https://github.com/profanis/codeShotsWithProfanis/tree/13/rxjsMapAndAsyncPipe
#angular #rxjs #observable #map #async
#angular rxjs #angular #angular tutorial #what is angular
1595344320
Corona Virus Pandemic has brought the world to a standstill.
Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.
Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!
And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!
If you are still not aware of it, don’t worry as Georgia Byng has well said,
“No time is better than the present”
– Georgia Byng, a British children’s writer, illustrator, actress and film producer.
No matter if you are a developer (be it front-end or back-end) or a data scientist, tester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.
From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.
Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.
These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.
Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).
xlr8rs make your development real fast by just adding your core business logic to the template.
If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂
To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.
Since we believe:
“There’s always a scope of improvement“
If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.
#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade
1573013179
Learn Error handling in Angular 8/9, we will take the best approach with RxJS catchError / catchError operators and HttpInterceptor to handle client-side errors gracefully.
A proper Error handling makes an application most helpful for users from the user experience aspect. Error handlers report a user correctly what causing the problem vise verse. It also notifies developers in the development phase about the error reason, which assists them to fix it before it goes live.
These days new technologies are growing faster than ever. This competition is all about making a piece of software better for users be it a final user, product owner or a developer who is building it from scratch. Due to this, user experiences became the trend.
There are two types of errors which might occur in an application, inside errors and outside errors.
Outside Errors: These errors often occur from the server-side and usually starts with (5xxx) status code. These errors return the error message with the proper reason so identifying these errors is easy.
Inside Error: When something unexpected happens, then these errors are thrown. These errors occur with the proper message, which contains the reason for the error occurrence.
Here is the complete List of HTTP status codes.
Next, we practically understand how to handle client-side errors in Angular. A Client-side error handling is one of the features among other various features for developing a user friendly application.
A user gets frustrated when suddenly an app stopped working, and the user doesn’t find the reason for it. It downgrades the overall user experience of the application. To enhance the user experience, we must properly handle errors.
We will use the regular error handling approaches such as handling errors with RxJS operators catchError and throwError and managing errors with HttpClient and HttpInterceptor.
The simplest way to handle errors in Angular is to use Angular’s HttpClient service along with RxJS operators throwError
and catchError
. Http request is made, and it returns the data with a response if anything wrong happens then it returns an error object with error status code.
Below is the service in which we used the handleError() function to handle errors in Angular.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
class Post {
constructor(
public id: string,
public title: string,
public body: string
) { }
}
@Injectable({
providedIn: 'root'
})
export class PostService {
private endpoint = 'https://jsonplaceholder.typicode.com/xyz';
constructor(private http: HttpClient) { }
getPost(): Observable<Post[]> {
return this.http.get<Post[]>(this.endpoint)
.pipe(
retry(1),
catchError(this.handleError)
);
}
handleError(error) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
}
In the service, we defined the handleError()
method. In this method, we are checking if the error is an instance of ErrorEvent
. This function returns either the client-side or server-side error. This error is useful for a single service. Still, when it comes to managing multiple services, then we have to update the handleError function in every service even for a minor change.
To handle errors properly HttpInterceptor is the best way, It intercepts Http request. It helps in converting http request before sending and after getting the response from the server. It is better used for updating data format, setting up headers, adding auth tokens etc. HttpInterceptor service offers better way to systematically handle errors in an Angular app.
The following ErrorIntercept service can manage multiple services. We are using retry(1) and catchError RxJS operators to check the HttpErrorResponse. This code is centralised in nature and can be managed from one place by far this has been the best way to manage errors in Angular.
Add the following code in error.interceptor.ts
:
import {
HttpEvent,
HttpHandler,
HttpRequest,
HttpErrorResponse,
HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
export class ErrorIntercept implements HttpInterceptor {
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Status: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
})
)
}
}
Import HttpClientmodule, HTTP_INTERCEPTORS and ErrorIntercept in app.module.ts
, next inject the HTTP_INTERCEPTORS and ErrorIntercept in providers array along with that set multi: true.
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorIntercept } from './error.interceptor';
@NgModule({
declarations: [...],
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorIntercept,
multi: true
}
],
bootstrap: [...]
})
export class AppModule { }
Here is the post.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
class Post {
constructor(
public id: string,
public title: string,
public body: string
) { }
}
@Injectable({
providedIn: 'root'
})
export class PostService {
private endpoint = 'https://jsonplaceholder.typicode.com/xyz';
constructor(private http: HttpClient) { }
getPost(): Observable<Post[]> {
return this.http.get<Post[]>(this.endpoint)
}
}
Finally we have completed error handling tutorial with examples, I hope this tutorial help you to understand the basic concept of handling client-side errors in Angular 8/9 with RxJS operators and HttpInterceptor.
#angular #web-development
1593184320
What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.
Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.
We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.
Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
bootstrap: [AppComponent]
})
Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:
#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular