Posts

Showing posts with the label angular

Angular: Create a workspace (Serie 1)

Prerequisites 1.1 Node.js According to the documentation , you need Node.js  (>10.9.0) installed on your computer. You can check the Node version with the following command: node -v . 1.2 npm We use the npm client command line shipped with Node.js to download and install npm packages. 1.3 Angular CLI Use the following command to install the Angular CLI globally: npm install -g @angular/cli You can find the available command reference here . Create a workspace and initial app In order to create a skeleton for an application named my-app , you only need to run the new command  as: ng new my-app The new command prompts you to select the routing mode, the style mode (css, scss...). Create a workspace under an existing folder For creating a workspace under an existing folder, do the following: open a terminal on your current folder (e.g. my-app) Run the following command : ng new my-app --directory=./ Run your app In order to buil...

Angular 7: A template to be up to speed in no time

Today, I'll share with you an Angular 7 application from where you can start building your own. I've followed as much as possible the best practices available here . You can find the source code at this repository . If you can improve this solution, do not hesitate to tell me. 😀 Let's inspect the different parts: Core Module 1. guards I've incorporated basically 2 guards:  The AuthGuard implements both CanActivate and CanLoad . This guard is responsible for checking if the current user is authenticated and authorized. If not authenticated, the user will be redirected to the login page. If the authenticated user hasn't sufficient permission, he will be redirected to the home page. The NoAuthGuard which implements CanActivate , provides a way to restrict a route when a user is already logged in (e.g. login). 2. interceptors The ErrorInterceptor basically intercepts client errors and server side errors. When it catches a 401 or 403 ...

Angular 7 | RxJS : Test finalize()

In the following interceptor, I want to test if the method loaderService.stopLoading() is properly called : As you can see this function is called from the finalize() RxJS operator. The unit test for this interceptor is as follow: Thanks for sharing...

Angular 7: Test Error Interceptor

Testing an error interceptor can be a little tricky. Below is the code I want to test : Basically we need to perform an HTTP request and respond with a mocking error for testing this interceptor. You need also to register it in the TestBed.configureTestingModule . Thanks for sharing...

Angular 7: Test Guard

Image
I will show you how you can test a guard. I'd like to test the code below: We have in this code mainly 3 cases to test: The logged in user has the required role. He should be able to access the restricted area. The logged in user has NOT the required role. He should not be able to access the restricted area. The user is redirected to the home page. The user is NOT logged in. He should not be able to access the restricted area. The user is redirected to the login page. You can run your test with ng test . You should see something like that: Thanks for sharing...

Exception Handling with Angular (6.0.7)

Our target : globally catch errors. The angular way to catch error globally is to implement a custom  ErrorHandler . Basically, I would like to act differently when we have server or client errors. When the server notifies an error, Angular throws an  HttpErrorResponse . For client-side error we will have an Error instance instead. When the user is not authorized (401), he may be redirected to the login page. When the user is not allowed to see a resource (403), he may be redirected to the forbidden page. 1. The errors service Basically, this service takes all errors information and send them to an endpoint (e.g. Help Desk). 2. The errors handler The router navigation should only be triggered inside Angular zone. 3. The core routing module Please take a look at my demo . Don't hesitate to share and comment...

Deploy Angular 2+ to GAE using Maven

Image
For a big project we have in my company, we needed to deploy an angular application (version 6) to the google cloud infrastructure (GAE). I'll show you step by step how you can deploy an angular application to the GAE by using Maven. My configuration: Java 8 and Maven 3.5 1. Create a GCP project Create a Google Cloud Project (GCP) through your Google Cloud Console . You will need the app ID for the following steps. You will need also to install the latest version of the App Engine SDK and add the directory to your PATH 2. Create a new project using maven command Go to the directory where you want to build the project and open a terminal at this location. On your terminal invoque this maven command to create an empty App Engine project: When prompted, you should accept default values (archetype, version...) and enter the groupId (your namespace), the artifactId (project name), version (accept default), package (accept default). When your project success...

Authentication and Authorization with Angular 2+

In this tutorial, I'll show you how you can secure your Angular 2+ application. Please, take a look at my previous post ( Authorization and Authentication with AngularJS + Jersey) for the backend implementation.   1. Authentication mechanism We use JWT (JSON Web Token) authentication mechanism in our application. We have decided to store our JWT in a cookie with HttpOnly (prevent XSS attacks) and Secure  (sent over HTTPS only). In order to prevent CSRF attack we'll use the double submit cookie .   This pattern is defined as sending a random value in both a cookie and as a request header. When a user authenticates to our application via the login page, the API responds with 2 cookies: A cookie (XSRF-TOKEN) set with a strong random value with Secure flag only.  We will instruct Angular HttpClient  to read this value and set it as an HTTP header (X-XSRF-TOKEN) for each subsequent request. Since only JavaScript that runs on your domain can read the cooki...

Angular Testing: routerLink

Today, I'll show you how you can test such a code: The routerLink directive on the anchor tag give the router control over this element. Find more info here . A. Provide the routerTestingModule with dummy routes as: B. Declare  Router and Location for use in your test: C. Routing is an asynchronous activity so we use one of the asynchronous testing methods at our disposal, in this case the fakeAsync method. Happy coding!!!

Angular Testing: ActivatedRoute

The route information and parameters are available through the ActivatedRoute service. While testing your components, it may be good to mock this service. 1. Mock ActivatedRoute If the user select an item within a list, the snapshot strategy can be used in your detail component. The route.snapshot provides the initial value of the route parameter map. The parameters can be accessed this way: The mocking service: 2. How to use? First we need to make available our ActivatedRouteStub in our test and pass testing parameters. So, in your test: 3. Mocking ActivatedRoute using a factory Using a factory is somewhat easier. In our component we have this code which we'd like to test: The test below uses a fake ActivatedRoute registered with the useFactory : Thanks

Custom chart creation with canvas and Angular

Image
Today, I'd like to show you how you can create a reusable chart using canvas HTML element and Angular. We are going to develop the following component : As you can see we have two series of data. The component will be used as follow: <custom-chart [data]="datasets"></custom-chart> Let's first create the service to set up the canvas 2D context and draw our chart. Chart Service We are going to create a service to set up our environment and draw on the canvas.  The data format should be: Chart Component We access the canvas reference using the @ViewChild annotation. We will use @Input annotation for data binding. We can easily add more functionality to our component, but for demonstration purpose it's enough.

Chip input using Reactive Form

The Chips component documentation from the angular material website, describes how to use the MatChipInput directive with a chip-list for adding or removing chips. I'll show you how you can implement the same component using Reactive Form. The HTML template: The TS component file:   As you can see, we use the FormBuilder class to simplify the form creation. We define our requirements as a  FormArray within our FormGroup. The requirements will be accessed in our template with this expression inside the *ngFor of <mat-chip></mat-chip> : *ngFor="let requirement of form.get('requirements').controls; let i = index;" In the ChipComponent class, the requirements array is accessed by using this expression: this.form.get('requirements') as FormArray; Thanks

Add Angular application to GIT repository

Generate an angular application is very easy with the angular CLI utility. Step 1. Set up the Development Environment Before processing you must have installed Node.js and npm to your computer. Install Angular CLI with the following commands:  npm install -g @angular/cli Step 2. Create a GIT repository After creating an empty GIT repository,  clone it to a new directory. git clone <your-repository>.git Step 3. Create a new Project Open or keep your terminal window on the parent folder of your local repository. Remove the README.md first otherwise the angular CLI will throw an error. Generate a skeleton application by running the following commands: ng new <your-repository-name> --directory <your-repository-name> The directory option tells the command line interface to create all required files in the existing folder.