Tech Point Fundamentals

Saturday, January 20, 2024

Angular Interview Questions and Answers - Part 18

Angular Interview Questions and Answers - Part 18

Angular-Interview-Questions-And-Answers

Angular is a popular open-source single-page application design framework and development platform. It is a robust front-end JavaScript framework that is widely used for front-end application development. Nowadays Angular is a very common frontend technology so it is very important for the interview point as well. 

Introduction


This is the Angular Interview Questions and Answers series. Here we will see 200+ Most Frequently Asked Angular Interview Questions. This is the 18th part of the Angular Interview Questions and Answer series.

I will highly recommend to please do visit the following parts before continuing to this part:



Please do visit our YouTube Channel here to watch Interview Questions & Answers and important technology videos.

In this part we will discuss the following Important Angular Interview Questions:

Q203. What is RxJS in Angular?
Q204. What is HttpClient in Angular? What are the advantages of using HttpClient?
Q205. What does mean by subscribing and unsubscribing in RxJS?
Q206. What is Promise in Angular? What are the different possible states of a Promise?
Q207. What is Observable in Angular? What is the use of observable in Angular?
Q208. What is Observer in Angular? How can you create an Observer?
Q209. What is the difference between observable and observer in Angular?
Q210. What will happen if you do not supply a handler for the Observer?
Q211. What is the difference between Promises vs. Observables in Angular?
Q212. What is an RxJS Subject in Angular?

Angular Interview Questions and Answers: Part 18


Q203. What is RxJS in Angular?

RxJS is an acronym that stands for Reactive Extensions for JavaScript. RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. RxJs is based on Observables, which are data streams that can be subscribed to and processed using operators.

RxJS is used in many popular frameworks, including Angular for pub-sub (publisher-subscriber) programming or reactive programming. Other programming languages, such as Java and Python, offer packages that allow them to develop reactive programs utilizing observables.

It is used to enable the use of observables in our JavaScript project, allowing us to do reactive programming.  It allows you to work with asynchronous data streams and handle events over time. It provides a powerful and flexible way to handle complex asynchronous operations in Angular. Many APIs such as HttpClient produce and consume RxJS Observables and also use operators for processing observables.

Reactive Programming is an asynchronous programming paradigm concerned with data streams and the propagation of change. RxJS provides an implementation of the Observable type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:

  • Converting existing code for async operations into observables
  • Iterating through the values in a stream
  • Mapping values to different types
  • Filtering streams
  • Composing multiple streams

Most of the time, RxJS is used in HTTP calls with Angular because HTTP streams are asynchronous data, we can subscribe to them and apply filters to them. You can import observables and operators from RxJs as follows for HTTP Client:

import { HttpClientModule } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

Q204. What is HttpClient in Angular? What are the advantages of using HttpClient?

Most of the front-end applications use either XMLHttpRequest interface or the fetch() API to communicate with backend services over HTTP protocol. For the same purpose, Angular provides a simplified client HTTP API known as HttpClient. This is based on top of XMLHttpRequest interface.

HttpClient is an Angular module used for communicating with a back-end service via the HTTP protocol. Usually, in front-end applications, for sending requests, we use the fetch API. However, the fetch API uses promises

This HTTP Client is available from the @angular/common/http package. You should import HttpClient into the root module after BrowserModule.

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

Promises are useful, but they do not offer the rich functionalities that observables offer. This is why we use HttpClient in Angular as it returns the data as an observable, which we can subscribe to, unsubscribe to, and perform several operations on using operators. Observables can be converted to promises, and an observable can be created from a promise as well.

Advantages of HTTP Client:

  • HttpClient contains testability features.
  • It provides typed request and response objects.
  • It can intercept requests and responses.
  • It supports Observalbe APIs.
  • HttpClient also supports streamlined error handling.

Q205. What does mean by subscribing and unsubscribing in RxJS?

In RxJS, a Subscription is an object that represents a disposable resource, usually the execution of an Observable. In RxJS, when using observables, we need to subscribe to an observable to use the data that flows through that observable. This data is generated from a publisher and is consumed by a subscriber

When we subscribe to an observable, we pass in a function for the data and another function for errors so that, in case there is some error, we can show some message or process the message in some way.

An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

A Subscription has one other important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription. When we create an observable, we have to subscribe to it to execute the observable. Conversely, when we unsubscribe, we do the reverse to stop the same execution flow.

import { Component } from '@angular/core';
import { interval } from 'rxjs';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.sass']
})
export class UserComponent {
   observable = interval(1000);
   subscription = this.observable.subscribe(x => console.log(x));  
}

In this example, interval(1000) creates an Observable that emits sequential numbers every 1 second. The subscribe method is called on this Observable with a callback function that logs each emitted value to the console.

  subscription.unsubscribe();

The unsubscribe method is called on the Subscription object returned by subscribe, which stops the ongoing execution of the Observable. Subscriptions can also be put together so that a call to an unsubscribe of one Subscription may unsubscribe multiple Subscriptions as well.

Q206. What is Promise in Angular? What are the different possible states of a Promise?

A Promise in Angular is a JavaScript object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It is a class-based object that is created using the new keyword and its constructor function.

In JavaScript, a promise is an object, that provides the surety that it will return something in the future. A promise object works only once,  either it will succeed or fail, but it won’t work twice. JavaScript is a synchronous programming language but we can make JavaScript asynchronous using callback functions. A callback function can also be attached to the Promise.

Promises are used to simplify deferred and asynchronous computations. They represent an operation that has not been completed yet and may be in one of four possible states: fulfilled, rejected, pending, or settled.

Setting up a Promise in JavaScript is easy using the ECMAScript 6 API. We defined the Promise object with a new keyword and it is also known as constructor. A Promise constructor is meant to be the executor, and it takes two parameters resolve and reject

  • The resolve() function is invoked when the asynchronous task is completed and renders the result of the assigned tasks.
  • The second function is a reject() function, which is invoked when the assigned task fails and returns the reason with the error object.

const promise = new Promise(function(resolve, reject) {
  console.log('Promise is invoked');
  setTimeout(function() {
    resolve('Promise returns message after 1.5 second!');
    reject('Promise has some error.');
  }, 1500);
});
promise.then(function(value) {
  console.log(value);  
});

States of Promise: A Promise has three possible states:

  1. Pending: It is the initial state, neither fulfilled nor rejected
  2. Fulfilled: The onFulfilled() will be invoked, corresponds to resolve()
  3. Rejected: The onRejected() will be invoked, corresponds to reject()

In Angular, Promises are commonly used with the HttpClient module to work with HTTP asynchronously. They provide a simple and consistent way to handle asynchronous operations, such as making HTTP requests or handling user input, without getting lost in a web of callbacks.


Q207. What is Observable in Angular? What is the use of observable in Angular?

One of the primary concepts in RxJS is observables. Observables represent a collection of values over time. They are used to model asynchronous data streams and can emit zero or more values, as well as signals indicating completion or error.

Observables are the core building blocks in RxJS and enable you to handle events, perform async operations, and process data in a declarative and composable way. Angular makes use of observables as an interface to handle a variety of common asynchronous operations.

Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. An Observable is a class-based object that is created using the new keyword and its constructor function.

Why Observable?

An observable is a declarative way using which we can perform asynchronous tasks. Observables can be thought of as streams of data flowing from a publisher to a subscriber. They are similar to promises as they both deal with handling asynchronous requests.

An Observable is a unique Object similar to a Promise that can help manage async code. Although, it is similar to a Promise in that it represents the eventual completion or failure of an asynchronous operation and its resulting value. However, Observables provide more features than Promises, such as the ability to cancel an operation, retry failed operations, and transform data using operators.

Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

Application of Observable:

In Angular, Observables are a powerful tool for handling asynchronous operations. They are used to represent a stream of data that can be observed over time. Observables can be used to handle a variety of common asynchronous operations, such as making HTTP requests or handling user input.

Observables can be used with the HttpClient module to work with HTTP asynchronously. They can also be used with the Router and Forms modules to listen for and respond to user-input events.

Creating and using Observable:

Use the Observable constructor to create an observable stream of any type. The constructor takes as its argument the subscriber function to run when the observable's subscribe() method executes. A subscriber function receives an Observer object and can publish values to the observer's next() method.

Observables are lazy so they run only when someone subscribes to them. An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

import { Observable } from "rxjs";

const observable = new Observable(observer => {
  setTimeout(()=>{
      observer.next('Message from Observable');
      observer.error('Observer got an error');
      observer.complete();
  },3000)
});

observable.subscribe((data)=> console.log(data));

Q208. What is Observer in Angular? How can you create an Observer?

We need to define a handler for receiving observable notifications which implements the Observer interface. It is an object that defines callback methods to handle the three types of notifications that an observable can send.

interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has three notification methods:

1. next: It is a required method. It is a handler for each delivered value. It is called zero or more times after execution starts. A next() function could receive, for instance, message strings, or event objects, numeric values, or structures, depending on context. As a general term, we refer to data published by an observable as a stream. Any type of value can be represented with an observable, and the values are published as a stream.

2. errorIt is an optional method. It is a handler for an error notification. An error halts the execution of the observable instance.

3. complete: It is also an optional method. This is a handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.

An observer object can define any combination of these handlers. If you don't supply a handler for a notification type, the observer ignores notifications of that type. A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable.

import { Observer, Observable, of } from "rxjs";

const numberObservable = of(1, 2, 3);

const myObserver = {
  next: (x: number) => console.log('Observer got a next value: ' + x),
  error: (err: Error) => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};

numberObservable.subscribe(myObserver);

Alternatively, the subscribe() method can accept callback function definitions in line, for next, error, and complete handlers.

Q209. What is the difference between observable and observer in Angular?

Observable: 

An observable is a unique object just like a promise that is used to manage async code. Observables are not part of the JavaScript language so the developers have to rely on a popular Observable library called RxJS. The observables are created using the new keyword.

import { Observable } from 'rxjs';

observable = new Observable(
observer => {  
              setTimeout(() => {  
              observer.next('Observable Message Received!');  
            }, 1000);  
});

Observer:

Observer is an interface for a consumer of push-based notifications delivered by an Observable. Any object that has to be notified when the state of another object changes is called an observer. An observer is an interface for push-based notifications delivered by an Observable.

interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

The handler that implements the observer interface for receiving observable notifications is passed as a parameter for observable. If you don't use a handler for a notification type, the observer ignores notifications of that type.

observable.subscribe(myObserver);

Q210. What will happen if you do not supply a handler for the Observer?

When a handler is not supplied to a notification type, the observer automatically ignores notifications of that type and the observer instance publishes values only when it is subscribed to.

Usually, an observer object can define any combination of next, error, and complete notification type handlers. If you don't supply a handler for a notification type, the observer just ignores notifications of that type.

Q211. What is the difference between Promises vs. Observables in Angular?

Although both promises and observables are used to handle asynchronous requests in JavaScript, they work in very different ways. Promises can only handle a single event at a time, while observables can handle a sequence of asynchronous events over a period of time.

The similarity between Observables and Promises is that both collections may produce values over time, but the difference is that Observables may produce none or more than one value, while Promises produce only one value when resolved successfully.

In Angular, as soon as we make a promise, the execution takes place eagerly, but this is not the case with observables because they are lazy. It means nothing happens until a subscription is made.

Promises emit a single value at a time. They execute immediately after creation and are non-cancellable. They push the errors to the child's promises as well. On the other hand, Observables are only executed when subscribed to them using the subscribe() method and it can emit multiple values over a period of time. Promise has different utility functions like forEachfilterretry, etc. 

A promise is just a way to wrap asynchronous operations so that they can be easily used, while an observable is a way to turn asynchronous operations into a stream of data that flows from a publisher to a subscriber through a well-defined path with multiple operations transforming the data along the way.

PromiseVsObservable


Q212. What is an RxJS Subject in Angular?

A Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast, Subjects are multicast. In Unicast each subscribed Observer owns an independent execution of the Observable.

In simple words, a Subject is a hot observable that can be used to broadcast events (multicast ) to multiple subscribers. It is similar to EventEmitters in that it maintains a registry of many listeners. There are also a few specializations of the Subject type: BehaviorSubject, ReplaySubject, and AsyncSubject.

Every Subject is an Observable:

This means that given a Subject, you can subscribe to it, providing an Observer, which will start receiving values normally. From the perspective of the Observer, it cannot tell whether the Observable execution is coming from a plain unicast Observable or a Subject. 

Internally to the Subject, subscribe does not invoke a new execution that delivers values. It simply registers the given Observer in a list of Observers, similar to how addListener usually works in other libraries and languages.

Every Subject is an Observer Too:

This means it is an object with the methods next(v), error(e), and complete(). To feed a new value to the Subject, just call next(theValue), and it will be multicasted to the Observers registered to listen to the Subject. Since a Subject is an Observer, this also means you can provide a Subject as the argument to the subscribe() method of any Observable.

import { Subject, from } from 'rxjs';

@Component({
  selector: 'app-user',
  template: `
    <button (click)="sendMessage()">Send Message</button>
    <app-child></app-child>
  `,
})
export class UserComponent
   subject = new Subject<string>();
   sendMessage() {
     this.subject.next('Hello Message : From Parent Component!');
   }
}

Here we created a new Subject instance and will use it to send messages to the child component when the button is clicked. The child component can subscribe to this Subject and receive messages as follows:

import { Component } from '@angular/core';
import { Subscription } from 'rxjs';
import { UserComponent } from '../user/user.component';

@Component({
  selector: 'app-child',
  template: `<p>{{ message }}</p>`
  styleUrls: ['./child.component.sass']
})
export class ChildComponent {
  message: String = '';
  subscription: Subscription;

  constructor(private appComponent: UserComponent) {
    this.subscription = appComponent.subject.subscribe((message) => {
      this.message = message;
    });
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}



Recommended Articles




Thanks for visiting this page. Please follow and join us on  LinkedInFacebookTelegramQuoraYouTubeTwitterInstagramWhatsApp, VKTumbler, and Pinterest for regular updates.

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.