Angular Interview Questions You Should Know

Part 6

Image for post
Image for post

45. Which RXJS Operators you use mostly to handle http services?

Below are the Most Commonly used RXJS Operators to handle HTTP Services in Angular.

SUBSCRIBE : subscribe is used to get the data from the observable.

const defaultRejectedPromise = () => new Promise((resolve, reject) => reject('defaultRejectedPromise!'));const sourceObs$ = from(defaultRejectedPromise());sourceObs$.subscribe(next => console.log(next));

CATCH ERROR : Catch Error operator is used to gracefully handle errors, returning observable with error messages as below.

Image for post
Image for post
const defaultRejectedPromise = () => new Promise((resolve, reject) => reject('defaultRejectedPromise!'));const sourceObs$ = from(defaultRejectedPromise());sourceObs$.pipe(catchError(error => of (`Bad Promise: ${error}`))).subscribe(next => console.log(next));

COMBINE LATEST

Combine Latest operator is used to emit only the latest values from multiple observable sources. Best used when we are trying to make a post API call with multiple filters triggered from different events such as buttons or drop down etc. The only thing to keep in mind while using this operator is that, combine latest will not emit an initial value until each observable emits at least one value.

Image for post
Image for post
initializeDetails(id: string): void {combineLatest([
this.service.getInitData(),
this.service.getDetails(id),
])
.pipe(
catchError((error: HttpErrorResponse) => {
return throwError(error);
}),
finalize(() =>
),
takeUntil(this._ngUnsubscribe$),
)
.subscribe(() => {});
}

DEBOUNCE TIME & DISTINCT UNTIL CHANGED

These two operators are commonly used together but they do not have to be piped together always. These operators are a perfect choice in scenarios such as type-ahead where the rate of user input must be controlled.

Image for post
Image for post
const input = document.querySelector('input');
const obs$ = fromEvent(input, 'input');
obs$.pipe(
map(event => event.target.value),
debounceTime(1000),
distinctUntilChanged())
.subscribe((value) => console.log(value));

TAP

Tap operator is more of a utility operator which can be used to perform transparent actions such as logging.

const obs$ = of (1, 2, 3, 4, 5);
obs$.pipe(
tap(val => console.log(`BEFORE MAP: ${val}`)),
map(val => val + 10),
tap(val => console.log(`AFTER MAP: ${val}`))
).subscribe(val => console.log(val));

SWITCH MAP

One of the main problems of using Javascript callbacks or promises is that they cannot cancel any long-running HTTP operations.

Consider the case where you selected a Netflix video to watch and just after few seconds, you changed your mind and quickly selected another video.

Even though you are not interested in the first video, the API call to fetch the first video will still continue and complete its operation in the background. It would be ideal to have an easy mechanism to cancel these stale events cleanly after some predetermined amount of time.

SwitchMap operator provides an easy mechanism to cancel these in-flight network requests. For example, look at the below code using switchMap operator.

Image for post
Image for post
const obs$1 = fromEvent(document, 'click');
const obs$2 = interval(1000);
const finalObs$ = obs$1.pipe(
switchMap(event => obs$2)
);
const subscription = finalObs$.subscribe((value) => console.log(value));

MAP & PLUCK

Map and Pluck are most used and very useful operators. Map operator in RxJS works similar to JS map. Pluck is used when we just need to pass single field value to the subscription instead of sending entire JSON object.

Image for post
Image for post
const data = [{
id: 1,
value: ‘one’
}, {
id: 2,
value: ‘two’
}, {
id: 3,
value: ‘three’
}];
const obsPluck$ = from(data).pipe(
pluck(‘value’)
).subscribe(x => console.log(x));
const obsMap$ = from(data).pipe(
map(data => data.value)
).subscribe(x => console.log(x));

FORK JOIN

forkJoin is an operator that takes any number of input observables which can be passed either as an array or a dictionary of input observables. If no input observables are provided, resulting stream will complete immediately.

forkJoin will wait for all passed observables to complete and then it will emit an array or an object with last values from corresponding observables.

Image for post
Image for post
const observable = forkJoin({
foo: of(1, 2, 3, 4),
bar: Promise.resolve(8),
baz: timer(4000),
});
observable.subscribe({
next: value => console.log(value),
complete: () => console.log('This is how it ends!'),
});

RETRY

Returns an Observable that mirrors the source Observable with the exception of an error. If the source Observable calls error, this method will resubscribe to the source Observable for a maximum of count resubscriptions (given as a number parameter) rather than propagating the error call.

Image for post
Image for post
const source = interval(1000);
const example = source.pipe(
mergeMap(val => {
if(val > 5){
return throwError('Error!');
}
return of(val);
}),
//retry 2 times on error
retry(2)
);

const subscribe = example.subscribe({
next: val => console.log(val),
error: val => console.log(`${val}: Retried 2 times then quit!`)
});

46. Which RXJS operators used for transforming or manipulating array of objects?

below are the most commonly used RXJS operators for transforming data.

SWITCH MAP

When we have requirements where we need to get the data from one observable and pass that data to call the service mostly it is used here, where switchmap make only one observable active at a time.

Image for post
Image for post
this.auQuery.currentData$
.pipe(
debounceTime(0),
switchMap((code) => {
return this.service.getData(
code as string
);
}),
catchError((error: HttpErrorResponse) => {
return throwError(error);
}),
finalize(() =>
takeUntil(this._ngUnsubscribe$),
)
.subscribe(() => {});
});

EXHAUST MAP

Returns an Observable that emits items based on applying a function that you supply to each item emitted by the source Observable, where that function returns an (so-called “inner”) Observable. When it projects a source value to an Observable, the output Observable begins emitting the items emitted by that projected Observable.

fromEvent(this.saveButton.nativeElement, 'click').pipe(exhaustMap(() => this.saveCourse(this.form.value))).subscribe();

REDUCE

Reduces the values from source observable to a single value that’s emitted when the source completes.

const source = of(1, 2, 3, 4);const example = source.pipe(reduce((acc, val) => acc + val));//output: Sum: 10'const subscribe = example.subscribe(val => console.log('Sum:', val));

TOARRAY

Collects all source emissions and emits them as an array when the source completes.

interval(100).pipe(take(10), toArray()).subscribe(console.log);

CONCATMAP

Map values to inner observable, subscribe and emit in order.

const source = of(2000, 1000);// map value from source into inner observable, when complete emit result and move to nextconst example = source.pipe(concatMap(val => of(`Delayed by: ${val}ms`).pipe(delay(val))));//output: With concatMap: Delayed by: 2000ms, With concatMap: Delayed by: 1000msconst subscribe = example.subscribe(val =>console.log(`With concatMap: ${val}`));

46. Discuss different decorators in Angular.

47. What are the lifecycle methods in Angular.

48. What are the best security practices you follow in Angular.

49. What is renderer 2?

50. What is Zone.js?

51. Discuss different pipes in Angular.

52. Explain how Angular application loads.

53. What is dependency injection in Angular

54. What is Race Condition?

Written by

Writing about Angular,JavaScript and Type Script related articles. Please follow, clap stories to motivate us writing more!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store