Tech Point Fundamentals

Saturday, January 27, 2024

Angular Interview Questions and Answers - Part 19

Angular Interview Questions and Answers - Part 19

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 19th 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:

Q213. What is the difference between Observable and Subject in Angular?
Q214. What is the difference between Multicasted Observables vs Unicasted Observables in Angular?
Q215. What is multicasting in Angular?
Q216. What is the difference between Multicasting vs. Publishing in Angular?
Q217. How do you handle the errors of async operations in Angular?
Q218. What are the different utility functions provided by the RxJS Library?
Q219. What are the RxJs Operators in Angular?
Q220. What are the different Observable creation functions in Angular?
Q221. How can you create an observable from a promise?
Q222. What is the use of the Map operator in Angular?
Q223. What is the use of the Pipe operator in Angular?

Angular Interview Questions and Answers: Part 19


Q213. What is the difference between Observable and Subject in Angular?

In Angular, Observables and Subjects are both used for handling asynchronous operations. They are both classes that represent a stream of data that can be observed over time.

The main difference between Observables and Subjects is that Observables are unicast, meaning that each subscribed Observer owns an independent execution of the Observable, while Subjects are multicast, meaning that they allow values to be multicast to many Observers.

Subjects are a special type of Observable that allows values to be pushed to multiple Observers, while plain Observables are unicast and can only be subscribed to by one Observer at a time.

Observable and Subject are both part of the RxJS library and are used for managing asynchronous data streams and event handling in Angular. However, they have some key differences.


ObservableVsSubject


Q214. What is the difference between Multicasted Observables vs Unicasted Observables in Angular?

In Angular, multicasted Observables and unicasted Observables are two types of Observables that differ in how they handle subscriptions.

Unicasted Observable is an Observable that creates a new execution of the Observable for each subscriber. In other words, each subscriber has its own independent execution of the Observable. This means that if you have multiple subscribers, each subscriber will receive its own copy of the data produced by the Observable.

On the other hand, a Multicasted Observable is an Observable that shares a single execution of the Observable among multiple subscribers. This means that all subscribers receive the same data produced by the Observable. In RxJS, 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. A Subject is like an Observable, but can multicast to many Observers.

A "multicasted Observable" passes notifications through a Subject which may have many subscribers, whereas a plain "unicast Observable" only sends notifications to a single Observer. The multicasted Observable uses a Subject under the hood to make multiple Observers see the same Observable execution. 

So under the hood: Observers subscribe to an underlying Subject, and the Subject subscribes to the source Observable.

The multicast operator is deprecated (removed) in v8 of RxJs. Now you can use the connect operator or the share operator instead for multicasting.

RxJS share() operator is a multicasting operator that returns a new observable that shares or multicasts the original observable. As long as there is at least one subscriber, this observable will be subscribed and emitting data. When all subscribers have unsubscribed, it will unsubscribe from the source observable. Because the observable is multicasting, it makes the stream hot. This is an alias for multicast(() => new Subject()), refCount().

The share() operator is a convenient way to multicast an Observable. It automatically manages the connection to the source Observable, keeping track of active subscribers. When the first subscriber subscribes, the share() operator internally subscribes to the source Observable. If subsequent subscribers subscribe while the source Observable is still active, they are automatically added to the multicast.

import { take, share  } from 'rxjs/operators';
import { from, Subject, interval } from 'rxjs';
 
let observer = interval(1000).pipe(take(5), share());  

const subscribe_one = observer.subscribe(  
   x => console.log("Value from Sub1 = "+x)  
);  
const subscribe_two = observer.subscribe(  
   x => console.log("Value from Sub2 = "+x)  
);  
setTimeout(() => {  
   const subscribe_three = observer.subscribe(  
      x => console.log("Value from Sub3 = "+x)  
   );  
}, 2000);  

Q215. What is multicasting in Angular?

Multicasting is a technique in Angular that allows you to broadcast to multiple subscribers in a single execution. It is a type of observable that reuses the first listener and sends values out to each subscriber without registering multiple listeners on the document.

Multicasting observables are useful when you want to share data streams among multiple subscribers. They provide an efficient way to control and optimize data handling in complex applications.

Multicasting basically means that one Observable execution is shared among multiple subscribers. We pass our Subject to the subscribe function and let it take the values that come out of the Observable. All the subscribers to that Subject will then immediately receive that value.

In Angular, when we use the HttpClient module to communicate with a backend service and fetch some data, after fetching the data, we can broadcast it to multiple subscribers in one execution. This task of responding with data to multiple subscribers is called multicasting.

It is specifically useful when we have multiple parts of our applications waiting for some data. To use multicasting, we need to use an RxJS subject. As observables are by default unicast, they do not allow multiple subscribers. However, subjects do allow multiple subscribers and are multicast. The main reason to use Subject is to multicast. 

import { Subject, interval, from } from 'rxjs';
import { take, share  } from 'rxjs/operators';

let observer = interval(1000).pipe(take(5), share());

const subscribe_one = observer.subscribe(  
  x => console.log("Value from Sub1 = "+x)  
);  
const subscribe_two = observer.subscribe(  
  x => console.log("Value from Sub2 = "+x)  
);

If you ever have a scenario where your Observable subscriptions receive different values, use Subjects. Subjects will make sure each subscription gets the exact same value as the Observable execution is shared among the subscribers. Subjects simultaneously hold and efficiently distribute the values according to scope and definition. 

Make sure to unsubscribe the Subject once you no longer need it, else it will result in a heavy memory leak. Otherwise, you can use ASYNC pipe to overcome the above memory leak problem.

const subject = new Subject();
subject.subscribe({
  next: (data) => console.log('First observer prints '+ data)
 });

 subject.next(1);

 subject.subscribe({
  next: (data) => console.log('Second observer prints '+ data)
 });

 subject.next(2);

Q216. What is the difference between Multicasting vs. Publishing in Angular?

In RxJS, both multicast and publish operators are used to share a single subscription to an observable among multiple subscribers. However, there is a subtle difference between the two.

In simple terms, publish is a special case of multicast. Publish always creates a new subject and then uses multicast to share the subscription. On the other hand, multicast uses the subject provided as an argument to share the subscription.

In other words, publish is a shorthand for multicast(new Subject()). Similarly, publishBehaviorpublishLast, and publishReplay are shorthands for multicast(new BehaviorSubject())multicast(new AsyncSubject()), and multicast(new ReplaySubject()), respectively.

Q217. How do you handle the errors of async operations in Angular?

We know that we can use try-catch to deal with errors but it is useless in an asynchronous context. However, you may manage exceptions by setting an error callback on the observer.

1. ErrorObject:

An error is when the request fails on the server or fails to reach the server due to network issues. In this condition, HttpClient returns an error object instead of a successful response. To resolve this issue, we must handle the component by passing the error object as a second callback to the subscribe() method.

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'),
};

2.  CatchError Operator:

In addition to the error() handler that you provide on subscription, RxJS provides the catchError operator that lets you handle known errors in the observable itself. When dealing with errors in observables, the catchError operator can be used to handle and recover from errors. This operator allows you to provide a fallback value or execute alternative logic when an error occurs.

You can also chain the catchError operator after the observable that might produce an error and define a callback function to handle the error. Within the callback function, you can perform error-handling tasks such as logging the error, displaying an error message to the user, or initiating a retry mechanism.

import { ajax } from 'rxjs/ajax';
import { map, retry, catchError } from 'rxjs/operators';

const apiData = ajax('/api/userData').pipe(
  retry(3),
  map(res => {
    if (!res.response) {
      throw new Error('Value expected!');
    }
    return res.response;
  }),
  catchError(err => of([]))
);
 
apiData.subscribe({
  next(x) { console.log('data: ', x); },
  error(err) { console.log('errors already caught... will not run'); }
});

3. Retry Operator:

catchError operator provides a simple path of recovery from an error, but the retry operator lets you retry a failed request. You can use the retry operator before the catchError operator

It resubscribes to the original source observable, which can then re-run the full sequence of actions that resulted in the error. If this includes an HTTP request, it will retry that HTTP request.

The retry operator takes a parameter, that specifies the no of times it should retry. In the above example, the retry(3) will retry up to 3 times.

Q218. What are the different utility functions provided by the RxJS Library?

RxJS provides a rich set of utility functions that can be used to create and work with observables. RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as eventstimers, and promises.

RxJs provide the following different types of utility:

  • 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

RxJsUtilityFunction


Q219. What are the RxJs Operators in Angular?

Operators are functions that build on the top of observables foundation to enable sophisticated manipulation of collections. Operators take configuration options, and they return a function that takes a source observable. 

When executing this returned function, the operator observes the source observable’s emitted values, transforms them, and returns a new observable of those transformed values.

RxJS provides many operators, but only a handful are used frequently. 

RxJsOperators

Q220. What are the different Observable creation functions in Angular?

Angular RxJs provide different ways to create observables. RxJS provides creation functions for the process of creating observables from promiseseventstimers, and Ajax requests. 

RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, and promises.

  • Create an observable from a promise
  • Create an observable that creates an AJAX request
  • Create an observable from a counter or interval
  • Create an observable from an event

Q221. How can you create an observable from a promise?

To create an observable from a promise, you can use the from operator provided by the RxJS library. The from operator can be used to convert an arraypromise, or iterable into an observable.


import { from } from 'rxjs';

const apiUserData = from(fetch('/api/userApiEndpoint'));

apiUserData.subscribe({
  next(response) { console.log(response); },
  error(err) { console.error('Error: ' + err); },
  complete() { console.log('Completed'); }
});

Similarly, you can create an observable that creates an AJAX request:

import { ajax } from 'rxjs/ajax';
 
const apiAjaxData = ajax('/api/data');
apiAjaxData.subscribe(res => console.log(res.status, res.response));

Q222. What is the use of the Map operator in Angular?

The map operator in Angular is used to transform the values emitted by an observable into new values. It applies a project function to each of the values emitted by the source observable and transforms them into a new value. It then emits the new value to the subscribers. To use a map, first, we need to import it from the rxjs/operators library.

The syntax of the map operator is as follows:

map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R>

Here, project is a function that we use to manipulate the values emitted by the source observable. The project function can accept two arguments. One is value, i.e., the value emitted by the observable. The second argument is the index number.

The index number starts with 0 for the first value emitted and is incremented by 1 for every subsequent value emitted. It is similar to the index of an array. thisArg is optional and its default value is undefined. It defines what this is in the project function.

import { map } from 'rxjs/operators';
 
const nums = of(1, 2, 3);
 
const squareValues = map((val: number) => val * val);
const squaredNums = squareValues(nums);
squaredNums.subscribe(x => console.log(x));

Q223. What is the use of the Pipe operator in Angular?

The pipe operator in Angular is used to transform data before displaying it in the view. It is a template expression operator that accepts an input value and returns a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.

The pipe operator is used to link together functional operators into a chain. Pipes let you combine multiple functions into a single function. It takes as its arguments the functions you want to combine and returns a new function that, when executed, runs the composed functions in sequence.

A set of operators applied to an observable is a recipe i.e. a set of instructions for producing the values you’re interested in. By itself, the recipe doesn’t do anything. You need to call subscribe() to produce a result through the recipe.

import { filter, map } from 'rxjs/operators';

const squareOddVals = numbers.pipe(
  filter((n: number) => n % 2 !== 0),
  map(n => n * n)
).subscribe( r => console.log(r));

The pipe() function is also a method on the RxJS Observable i.e. Observable.pipe(), so you use this shorter form to define the same operation:

import { filter, map } from 'rxjs/operators';
 
const squareOdd = of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 !== 0),
    map(n => n * n)
  );
 
squareOdd.subscribe(x => console.log(x));



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.