Angular Interview Questions Part 6

What are the types of injector hierarchies?

There are two types of injector hierarchies in Angular

  1. Module Injector hierarchy: It configure on a module level using an @NgModule() or @Injectable() annotation.
  2. Element Injector hierarchy: It created implicitly at each DOM element. Also it is empty by default unless you configure it in the providers property on @Directive() or @Component().

What are reactive forms?

Reactive forms is a model-driven approach for creating forms in a reactive style(form inputs changes over time). These are built around observable streams, where form inputs and values are provided as streams of input values. Let’s follow the below steps to create reactive forms,

  1. Register the reactive forms module which declares reactive-form directives in your app
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }

Create a new Form Control instance and save it in the component.

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'user-profile',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
  userName = new FormControl('');
}

Register the Form Control in the template.

<label>
  User name:
  <input type="text" [formControl]="userName">
</label>

Finally, the component with reactive form control appears as below, “`js import { Component } from ‘@angular/core’; import { Form Control } from ‘@angular/forms’;

@Component({
  selector: 'user-profile',
  styleUrls: ['./user-profile.component.css']
  template: `
     <label>
       User name:
       <input type="text" [formControl]="userName">
     </label>
  `
})
export class UserProfileComponent {
  userName = new FormControl('');
}
```

What are dynamic forms?

Dynamic forms is a pattern in which we build a form dynamically based on metadata that describes a business object model. You can create them based on reactive form API.

Angular Interview Question

What are template driven forms?

Template driven forms are model-driven forms where you write the logic, validations, controls etc., in the template part of the code using directives. They are suitable for simple scenarios and uses two-way binding with [(ng Model)] syntax. For example, you can create register form easily by following the below simple steps,

  1. Import the Forms Module into the Application module’s imports array
 import { BrowserModule } from '@angular/platform-browser';
   import { NgModule } from '@angular/core';
   import {FormsModule} from '@angular/forms'
   import { RegisterComponent } from './app.component';
   @NgModule({
     declarations: [
       RegisterComponent,
     ],
     imports: [
       BrowserModule,
       FormsModule
     ],
     providers: [],
     bootstrap: [RegisterComponent]
   })
   export class AppModule { }

Bind the form from template to the component using ng Model syntax

<input type="text" class="form-control" id="name"
       required
       [(ngModel)]="model.name" name="name">

Attach Ng Form directive to the tag in order to create Form Control instances and register them

<form #registerForm="ngForm">

Apply the validation message for form controls

<label for="name">Name</label>
<input type="text" class="form-control" id="name"
       required
       [(ngModel)]="model.name" name="name"
       #name="ngModel">
<div [hidden]="name.valid || name.pristine"
     class="alert alert-danger">
  Please enter your name
</div>

Let’s submit the form with ng Submit directive and add type=”submit” button at the bottom of the form to trigger form submit.

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
// Form goes here
<button type="submit" class="btn btn-success" [disabled]="!registerForm.form.valid">Submit</button>

Finally, the completed template-driven registration form will be appeared as follow.

```html
<div class="container">
    <h1>Registration Form</h1>
    <form (ngSubmit)="onSubmit()" #registerForm="ngForm">
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name"
               required
               [(ngModel)]="model.name" name="name"
               #name="ngModel">
        <div [hidden]="name.valid || name.pristine"
             class="alert alert-danger">
          Please enter your name
        </div>
      </div>
            <button type="submit" class="btn btn-success" [disabled]="!registerForm.form.valid">Submit</button>
    </form>
</div>
```

What are the differences between reactive forms and template driven forms?

Below are the main differences between reactive forms and template driven forms

FeatureReactiveTemplate-Driven
Form model setupCreated (Form control instance) in component explicitlyCreated by directives
Data updatesSynchronousAsynchronous
Form custom validationDefined as FunctionsDefined as Directives
TestingNo interaction with change detection cycleNeed knowledge of the change detection process
MutabilityImmutable(by always returning new value for Form Control instance)Mutable(Property always modified to new value)
ScalabilityMore scalable using low-level APIsLess scalable using due to abstraction on APIs

What are the different ways to group form controls?

Reactive forms provide two ways of grouping multiple related controls.

  1. Form Group: It defines a form with a fixed set of controls those can be managed together in an one object. It has same properties and methods similar to a Form Control instance. This Form Group can be nested to create complex forms as below.
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
  userProfile = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
          street: new FormControl(''),
          city: new FormControl(''),
          state: new FormControl(''),
          zip: new FormControl('')
        })
  });

  onSubmit() {
    // Store this.userProfile.value in DB
  }
}
<form [formGroup]="userProfile" (ngSubmit)="onSubmit()">

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label>

  <label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label>

  <div formGroupName="address">
    <h3>Address</h3>

    <label>
      Street:
      <input type="text" formControlName="street">
    </label>

    <label>
      City:
      <input type="text" formControlName="city">
    </label>

    <label>
      State:
      <input type="text" formControlName="state">
    </label>

    <label>
      Zip Code:
      <input type="text" formControlName="zip">
    </label>
   </div>
    <button type="submit" [disabled]="!userProfile.valid">Submit</button>

</form>

FormArray: It defines a dynamic form in an array format, where you can add and remove controls at run time. This is useful for dynamic forms when you don’t know how many controls will be present within the group.

 import { Component } from '@angular/core';
 import { FormArray, FormControl } from '@angular/forms';

 @Component({
   selector: 'order-form',
   templateUrl: './order-form.component.html',
   styleUrls: ['./order-form.component.css']
 })
 export class OrderFormComponent {
   constructor () {
     this.orderForm = new FormGroup({
       firstName: new FormControl('John', Validators.minLength(3)),
       lastName: new FormControl('Rodson'),
       items: new FormArray([
         new FormControl(null)
       ])
     });
   }

   onSubmitForm () {
     // Save the items this.orderForm.value in DB
   }

   onAddItem () {
     this.orderForm.controls
     .items.push(new FormControl(null));
   }

   onRemoveItem (index) {
     this.orderForm.controls['items'].removeAt(index);
   }
 }

Advance Angular Interview Question

How do you update specific properties of a form model?

You can use patchValue() method to update specific properties defined in the form model. For example, you can update the name and street of certain profile on click of the update button as shown below.

updateProfile() {
  this.userProfile.patchValue({
    firstName: 'John',
    address: {
      street: '98 Crescent Street'
    }
  });
}
<button (click)="updateProfile()">Update Profile</button>

You can also use set Value method to update properties.

Note: Remember to update the properties against the exact model structure.

What is the purpose of Form Builder?

Form Builder is used as syntactic sugar for easily creating instances of a Form Control, Form Group, or Form Array. This is helpful to reduce the amount of boilerplate needed to build complex reactive forms. It is available as an injectable helper class of the @angular/forms package.

For example, the user profile component creation becomes easier as shown here.

export class UserProfileComponent {
  profileForm = this.formBuilder.group({
    firstName: [''],
    lastName: [''],
    address: this.formBuilder.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
  });
  constructor(private form Builder: Form Builder) { }
  }

How do you verify the model changes in forms?

You can add a getter property(let’s say, diagnostic) inside component to return a JSON representation of the model during the development. This is useful to verify whether the values are really flowing from the input box to the model and vice versa or not.

export class UserProfileComponent {

  model = new User('John', 29, 'Writer');

  // TODO: Remove after the verification
  get diagnostic() { return JSON.stringify(this.model); }
}

and add diagnostic binding near the top of the form

{{diagnostic}}
<div class="form-group">
  // FormControls goes here
</div>

Angular Interview Question

What are the state CSS classes provided by ng Model?

The ng Model directive updates the form control with special Angular CSS classes to reflect it’s state. Let’s find the list of classes in a tabular format,

Form control stateIf trueIf false
Visitedng-touchedng-untouched
Value has changedng-dirtyng-pristine
Value is validng-validng-invalid

How do you reset the form?

In a model-driven form, you can reset the form just by calling the function reset() on our form model. For example, you can reset the form model on submission as follows,

onSubmit() {
  if (this.myform.valid) {
    console.log("Form is submitted");
    // Perform business logic here
    this.myform.reset();
  }
}

Now, your form model resets the form back to its original pristine state.

What are the types of validator functions?

In reactive forms, the validators can be either synchronous or asynchronous functions,

  1. Sync validators: These are the synchronous functions which take a control instance and immediately return either a set of validation errors or null. Also, these functions passed as second argument while instantiating the form control. The main use cases are simple checks like whether a field is empty, whether it exceeds a maximum length etc.
  2. Async validators: These are the asynchronous functions which take a control instance and return a Promise or Observable that later emits a set of validation errors or null. Also, these functions passed as second argument while instantiating the form control. The main use cases are complex validations like hitting a server to check the availability of a username or email.

The representation of these validators looks like below

this.myForm = formBuilder.group({
    firstName: ['value'],
    lastName: ['value', *Some Sync validation function*],
    email: ['value', *Some validation function*, *Some asynchronous validation function*]
});

Angular Interview Question

Can you give an example of built-in validators?

In reactive forms, you can use built-in validator like required and minlength on your input form controls. For example, the registration form can have these validators on name input field

this.registrationForm = new FormGroup({
    'name': new FormControl(this.hero.name, [
      Validators.required,
      Validators.minLength(4),
    ])
  });

Whereas in template-driven forms, both required and minlength validators available as attributes.

How do you optimize the performance of async validators?

Since all validators run after every form value change, it creates a major impact on performance with async validators by hitting the external API on each keystroke. This situation can be avoided by delaying the form validity by changing the update On property from change (default) to submit or blur. The usage would be different based on form types,

  1. Template-driven forms: Set the property on ngModelOptions directive
<input [(ngModel)]="name" [ngModelOptions]="{updateOn: 'blur'}">

Reactive-forms: Set the property on FormControl instance

name = new FormControl('', {updateOn: 'blur'});

How to set ng For and ng If on the same element?

Sometimes you may need to both ng For and ng If on the same element but unfortunately you are going to encounter below template error.

Template parse errors: Can't have multiple template bindings on one element.

In this case, You need to use either ng-container or ng-template. Let’s say if you try to loop over the items only when the items are available, the below code throws an error in the browser

<ul *ngIf="items" *ngFor="let item of items">
  <li></li>
</ul>

and it can be fixed by

<ng-container *ngIf="items">
  <ul *ngFor="let item of items">
    <li></li>
  </ul>
</ng-container>

Angular Interview Question

What is host property in CSS?

The :host pseudo-class selector is used to target styles in the element that hosts the component. Since the host element is in a parent component’s template, you can’t reach the host element from inside the component by other means. For example, you can create a border for parent element as below,

//Other styles for app.component.css
//...
:host {
  display: block;
  border: 1px solid black;
  padding: 20px;
}

How do you get the current route?

In Angular, there is an URL property of router package to get the current route. You need to follow the below few steps,

  1. Import Router from @angular/router
import { Router } from '@angular/router';

Inject router inside constructor

constructor(private router: Router ) {

}

Access URL parameter

console.log(this.router.url); //  /routename

What is Component Test Harnesses?

A component harness is a testing API around an Angular directive or component to make tests simpler by hiding implementation details from test suites. This can be shared between unit tests, integration tests, and end-to-end tests. The idea for component harnesses comes from the Page Object pattern commonly used for integration testing.

Angular Interview Question

What is the benefit of Automatic Inlining of Fonts?

During compile time, Angular CLI will download and inline the fonts that your application is using. This performance update speed up the first content ful paint(FCP) and this feature is enabled by default in apps built with version 11.

Enumerate some salient features of Angular 7.

Unlike the previous versions of Angular, the 7th major release comes with splitting in @angular/core. This is done in order to reduce the size of the same. Typically, not each and every module is required by an Angular developer. Therefore, in Angular 7 each split of the @angular/core will have no more than 418 modules.

Also, Angular 7 brings drag-and-drop and virtual scrolling into play. The latter enables loading as well as unloading elements from the DOM. For virtual scrolling, the latest version of Angular comes with the package. Furthermore, Angular 7 comes with a new and enhanced version of the ng-compiler.

What is string interpolation in Angular?

Also referred to as moustache syntax, string interpolation in Angular refers to a special type of syntax that makes use of template expressions in order to display the component data. These template expressions are enclosed within double curly braces i.e. {{ }}.

The JavaScript expressions that are to be executed by Angular are added within the curly braces and the corresponding output is embedded into the HTML code. Typically, these expressions are updated and registered like watches as a part of the digest cycle.

Advance Angular Interview Question

Explain Angular Authentication and Authorization.

The user login credentials are passed to an authenticate API, which is present on the server. Post server-side validation of the credentials, a JWT (JSON Web Token) is returned. The JWT has information or attributes regarding the current user. The user is then identified with the given JWT. This is called authentication.

Post logging-in successfully, different users have a different level of access. While some may access everything, access for others might be restricted to only some resources. The level of access is authorization.

Explain what is the difference between Angular and backbone.js?

Following are the various notable differences between Angular and Backbone.js

  • Architecture

Backbone.js makes use of the MVP architecture and doesn’t offer any data binding process. Angular, on the contrary, works on the MVC architecture and makes use of two-way data binding for driving application activity.

  • Community Support

Being backed by Google greatly ups the community support received by the Angular framework. Also, extensive documentation is available. Although Backbone.js has a good level of community support, it only documents on Underscore.js templates, not much else.

  • Data Binding

Angular uses two-way data binding process and thus is a bit complex. Backbone.js, on the contrary, doesn’t have any data binding process and thus, has a simplistic API.

  • DOM

The prime focus of Angular JS is upon valid HTML and dynamic elements that imitate the underlying data for rebuilding the DOM as per the specified rules and then works on the updated data records.

Backbone.js follows the direct DOM manipulation approach for representing data and application architecture changes.

  • Performance

Thanks to its two-way data binding functionality, Angular offers an impactful performance for both small and large projects.

Backbone.js has a significant upper hand in performance over Angular in small data sets or small webpages. However, it is not recommended for larger webpages or large data sets due to the absence of any data binding process.

  • Templating

Angular supports templating via dynamic HTML attributes. These are added to the document to develop an easy to understand application at a functional level. Unlike Angular, Backbone.js uses Underscore.js templates that aren’t fully-featured as Angular templates.

  • The Approach to Testing

The approach to testing varies greatly between Angular and Backbone.js due to the fact that while the former is preferred for building large applications the latter is ideal for developing smaller webpages or applications.

For Angular, unit testing is preferred and the testing process is smoother through the framework. In the case of Backbone.js, the absence of a data binding process allows for a swift testing experience for a single page and small applications.

  • Type

Angular is an open-source JS-based front-end web application framework that extends HTML with new attributes. On the other hand, Backbone.js is a lightweight JavaScript library featuring a RESTful JSON interface and MVP framework.

Could you explain the concept of templates in Angular?

Written with HTML, templates in Angular contains Angular-specific attributes and elements. Combined with information coming from the controller and model, templates are then further rendered to cater the user with the dynamic view.

Advance Angular Interview Question

Explain the difference between an Annotation and a Decorator in Angular?

 In Angular, annotations are used for creating an annotation array. They are only metadata set of the class using the Reflect Metadata library.

Decorators in Angular are design patterns used for separating decoration or modification of some class without changing the original source code.

What are the building blocks of Angular?

 There are essentially 9 building blocks of an Angular application. These are:

  1. Components – A component controls one or more views. Each view is some specific section of the screen. Every Angular application has at least one component, known as the root component. It is bootstrapped inside the main module, known as the root module. A component contains application logic defined inside a class. This class is responsible for interacting with the view via an API of properties and methods.
  2. Data Binding – The mechanism by which parts of a template coordinates with parts of a component is known as data binding. In order to let Angular know how to connect both sides (template and its component), the binding markup is added to the template HTML.
  3. Dependency Injection (DI) – Angular makes use of DI to provide required dependencies to new components. Typically, dependencies required by a component are services. A component’s constructor parameters tell Angular about the services that a component requires. So, a dependency injection offers a way to supply fully-formed dependencies required by a new instance of a class.
  4. Directives – The templates used by Angular are dynamic in nature. Directives are responsible for instructing Angular about how to transform the DOM when rendering a template. Actually, components are directives with a template. Other types of directives are attribute and structural directives.
  5. Metadata – In order to let Angular know how to process a class, metadata is attached to the class. For doing so decorators are used.
  6. Modules – Also known as NgModules, a module is an organized block of code with a specific set of capabilities. It has a specific application domain or a workflow. Like components, any Angular application has at least one module. This is known as the root module. Typically, an Angular application has several modules.
  7. Routing – An Angular router is responsible for interpreting a browser URL as an instruction to navigate to a client-generated view. The router is bound to links on a page to tell Angular to navigate the application view when a user clicks on it.
  8. Services – A very broad category, a service can be anything ranging from a value and function to a feature that is required by an Angular app. Technically, a service is a class with a well-defined purpose.
  9. Template – Each component’s view is associated with its companion template. A template in Angular is a form of HTML tags that lets Angular know that how it is meant to render the component.

Please explain the differences between Angular and jQuery?

The single biggest difference between Angular and jQuery is that while the former is a JS frontend framework, the latter is a JS library. Despite this, there are some similarities between the two, such as both features DOM manipulation and provides support for animation.

Nonetheless, notable differences between Angular and jQuery are:

  • Angular has two-way data binding, jQuery does not
  • Angular provides support for RESTful API while jQuery doesn’t
  • jQuery doesn’t offer deep linking routing though Angular supports it
  • There is no form validation in jQuery whereas it is present in Angular

Angular Interview Question

What are the biggest advantages of using Angular?

Following is the list of the biggest advantages of using the Angular framework:

  • Angular supports two-way data-binding.
  • It follows MVC pattern architecture.
  • It supports static templates and Angular template.
  • It facilitates you to add a custom directive.
  • It also supports REST full services.
  • Validations are supported in Angular.
  • Angular provides client and server communication.
  • It provides support for dependency injection.
  • It provides powerful features like Event Handlers, Animation, etc.

What do you understand by Angular expressions?

Angular expressions are code snippets that are used to bind application data to HTML. Angular expressions are usually placed in binding such as {{ expression }} similar to JavaScript.\

Syntax: {{ expression }}

What are templates in Angular?

In Angular, templates contain Angular-specific elements and attributes. These are written with HTML and combined with information coming from the model and controller, which are further rendered to provide the user’s dynamic view.

Advance Angular Interview Question

What is the difference between an Annotation and a Decorator in Angular?

In Angular, annotations are the “only” metadata set of the class using the Reflect Metadata library. They are used to create an “annotation” array. On the other hand, decorators are the design patterns used for separating decoration or modification of a class without actually altering the original source code.

What are the different Lifecycle hooks of Angular?

When the Angular components are created, they enter their lifecycle and remain when they are destroyed. Angular Lifecycle hooks are used to check the phases and trigger changes at specific phases during the entire duration.

ng On Changes( ): This method is called when one or more input properties of the component are changed. The hook receives a Simple Changes object containing the previous and current values of the property.

ng OnInit( ): This is the second lifecycle hook. It is called once, after the ng On Changes hook. It is used to initialize the component and sets the input properties of the component.

ng Do Check( ): This hook is called after ng On Changes and ng OnInit and is used to detect and act on changes that cannot be detected by Angular. In this hook, we can implement our change detection algorithm.

ng After ContentInit( ): This hook is called after the first ng Do Check hook. This hook responds after the content gets projected inside the component.

ng After Content Checked( ): This hook is called after ng After ContentInit and every subsequent ng Do Check. It responds after the projected content is checked.

ngAfterViewInit( ): This hook is called after a component’s view or the initialization of a child component’s view.

ng After View Checked( ): This hook is called after ng AfterViewInit. It responds after the component’s view or when the child component’s view is checked.

ng On Destroy( ): This hook is called just before Angular destroys the component. This is used to clean up the code and detach event handlers.

What are the biggest advantages of AOT in Angular?

Following are the advantages of using the AOT compiler in Angular:

The rendering is faster: When we use the AOT compiler, the browser gets a pre-compiled version of the application to download. Here, the browser loads executable code to render the application immediately, without waiting to compile the app first.

The Angular framework’s download size is smaller: AOT facilitates you not to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.

Fewer asynchronous requests: The compiler is used to inline external HTML templates and CSS style sheets within the application JavaScript so, it eliminates separate AJAX requests for those source files.

Detect template errors earlier: While using the AOT compiler, developers can easily detect and report template binding errors during the build step before users can see them.

Better security: AOT provides better security because it compiles HTML templates and components into JavaScript files before they are served to the client. Because there are no templates to read and no risky client-side HTML or JavaScript evaluation, so the chances for injection attacks are very rare.

Advance Angular Interview Question

What is View Encapsulation?

Component CSS styles are encapsulated into the component’s view to avoid styling side effects in the rest of the Angular application.

The type of encapsulation can be controlled per component via the encapsulation property in the component metadata:

// warning: few browsers support shadow DOM encapsulation at this time
encapsulation: ViewEncapsulation.ShadowDom
  • ViewEncapsulation.Emulated which is the default mode and emulates the shadow DOM behavior. It renames and preprocesses the CSS code to effectively scope the CSS to the component’s view. Each DOM element gets attached some additional attributes like _nghost or _ngcontent. An element that would be a shadow DOM host in native encapsulation has a generated _nghost attribute. This is typically the case for component host elements. An element within a component’s view has a _ngcontent attribute that identifies to which host’s emulated shadow DOM this element belongs.
  • ViewEncapsulation.None which tells Angular to not use view encapsulation and adds CSS to the global styles. Essentially, this is the same behavior as pasing the component’s styles into the HTML.

How do you chain pipes?

You can chain pipes together in potentially useful combinations as per the needs. Let’s take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below

import { Component } from '@angular/core';
        @Component({
          selector: 'app-birthday',
          template: `<p>Birthday is {{  birthday | date:'fullDate' | uppercase}} </p>` // THURSDAY, JUNE 18, 1987
        })
        export class BirthdayComponent {
          birthday = new Date(1987, 6, 18);
        }

What is a custom pipe?

Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,

  1. A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example,
 @Pipe({name: 'myCustomPipe'})

The pipe class implements the Pipe Transform interface’s transform method that accepts an input value followed by optional parameters and returns the transformed value. The structure of pipe Transform would be as below,

interface PipeTransform {
  transform(value: any, ...args: any[]): any
}

The @Pipe decorator allows you to define the pipe name that you’ll use within template expressions. It must be a valid JavaScript identifier.

template: `{{someInputValue | myCustomPipe: someOtherValue}}`

Angular Interview Question

Give an example of custom pipe?

You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension,

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'customFileSizePipe'})
export class FileSizePipe implements PipeTransform {
  transform(size: number, extension: string = 'MB'): string {
    return (size / (1024 * 1024)).toFixed(2) + extension;
  }
}

Now you can use the above pipe in template expression as below,

template: `
    <h2>Find the size of a file</h2>
    <p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
  `

What is HTTP Client and its benefits?

Most of the Front-end applications communicate with backend services over HTTP protocol using either XML Http Request interface or the fetch() API. Angular provides a simplified client HTTP API known as Http Client which is based on top of XML Http Request interface. This client is available from @angular/common/http package. You can import in your root module as below,

import { HttpClientModule } from '@angular/common/http';

The major advantages of HTTP Client can be listed as below,

  1. Contains testability features
  2. Provides typed request and response objects
  3. Intercept request and response
  4. Supports Observable APIs
  5. Supports streamlined error handling

Explain on how to use HTTP Client with an example?

Below are the steps need to be followed for the usage of HttpClient.

  1. Import Http Client into root module:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  ......
  })
 export class AppModule {}

Inject the HTTP Client into the application: Let’s create a user Profile Service(userprofile.service.ts) as an example. It also defines get method of HTTP Client

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const userProfileUrl: string = 'assets/data/profile.json';
@Injectable()
export class UserProfileService {
  constructor(private http: HttpClient) { }
}
getUserProfile() {
  return this.http.get(this.userProfileUrl);
}

Create a component for subscribing service: Let’s create a component called User Profile Component (user profile.component.ts) which inject User Profile Service and invokes the service method,

fetchUserProfile() {
  this.userProfileService.getUserProfile()
    .subscribe((data: User) => this.user = {
        id: data['userId'],
        name: data['firstName'],
        city:  data['city']
    });
}

Since the above service method returns an Observable which needs to be subscribed in the component.

Advance Angular Interview Question

How can you read full response?

The response body doesn’t may not return full response data because sometimes servers also return special headers or status code which which are important for the application workflow. In order to get full response, you should use observe option from HTTP Client,

getUserResponse(): Observable<HttpResponse<User>> {
  return this.http.get<User>(
    this.userUrl, { observe: 'response' });
}

Now Http Client. Get() method returns an Observable of typed Http Response rather than just the JSON data.

How do you perform Error handling?

If the request fails on the server or failed to reach the server due to network issues then HTTP Client will return an error object instead of a successful response. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method. Let’s see how it can be handled in the component with an example,

fetchUser() {
  this.userService.getProfile()
    .subscribe(
      (data: User) => this.userProfile = { ...data }, // success path
      error => this.error = error // error path
    );
}

It is always a good idea to give the user some meaningful feedback instead of displaying the raw error object returned from Http Client.

Angular Part 1Angular Part 2Angular Part 3Angular Part 4Angular Part 5
Back to top