Tech Point Fundamentals

Saturday, January 6, 2024

Angular Interview Questions and Answers - Part 16

Angular Interview Questions and Answers - Part 16

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

Q183. What is the providers array in Angular? What is the difference between provide and provider properties in Angular?
Q184. What are the different types of providers in Angular?
Q185. What is a Class Provider in Angular DI System? What is the purpose of useClass in Angular?
Q186. What is a Value Provider in Angular DI System? What is the difference between Value Provider vs. Factory Provider in Angular?
Q187. What is a Factory Provider in Angular DI System? What is the use of deps array in the Factory Provider of Angular?
Q188. What is an Aliased Provider in Angular DI System? What is the difference between useExisting vs. useClass in Angular?
Q189. Can you add multiple providers for the same DI token in Angular?  How can you use multiple providers with the same token in Angular?
Q190. What is the difference between multi-provider and regular provider in Angular?
Q191. What is the difference between StaticProvider vs. Provider in Angular?
Q192. What is the difference between the providers array vs. deps array for registering services in Angular?
Q193. What is the difference between the Providers Array and viewProviders Array in Angular?

Angular Interview Questions and Answers: Part 16


Q183. What is the providers array in Angular? What is the difference between provide and provider properties in Angular?

Angular provider is used to provide an instance of the dependency, we need to register it in the providers metadata i.e. Providers arrays. Providers allow us to register classes, functions, or values (dependencies) with the Angular Dependency Injection system. 

The Angular provider is an instruction that describes how an object for a certain token is created. In Angular providers is an array of such instructions (provider). Each provider is uniquely identified by a token (or DI  Token ) in the Providers array.

We register the services participating in the dependency injections in the Providers metadata. There are two ways by which we can do it:

  • Register directly in the Providers array of the @NgModule or @Component or in @Directive. 
  • Use the providedIn property of the @Injectable decorator.

These providers are registered using the token. The tokens are used to locate the provider. We can create three types of tokens: Type TokenString Token, and Injection Token.

import { UserService } from '../user-service.service';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  providers: [UserService],
})
export class UserModule{ }


The above providers array is an actual shorthand notation for the following syntax:

import { UserService } from '../user-service.service';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  providers :[{ provide: UserService, useClass: UserService }]
})
export class UserModule{ }

Here the above syntax has two properties: Provide vs Provider. 

Provide: The first property is Provide holds the Token or DI Token.  The Injector uses the token to locate the provider in the Providers array. The Token can be either a type, a string, or an instance of InjectionToken.

Provider: The second property is the Provider definition object. It tells Angular how to create the instance of the dependency. Angular can create the instance of the dependency in four different ways i.e. useClassuseValueuseFactory, or useExisting.


Q184. What are the different types of providers in Angular?

The provider tells Angular how to create the instance of the dependency.  The Angular can create the instance of the dependency in four different ways.

Types of Angular Providers:

There are four ways by which you can create the service dependency:

  1. Class Provider (useClass)
  2. Value Provider (useValue)
  3. Factory Provider (useFactory)
  4. Aliased Class Provider ( useExisting)

Each Injector gets its own copy of the providers. We can use the same dependency with multiple providers. The Injector reads the dependencies and looks for the provider in the providers array using the Token.

Q185. What is a Class Provider in Angular DI System? What is the purpose of useClass in Angular?

Class Provider (useClass):

We use the Class Provider useClass, when we want to provide an instance of the provided class. The useClass expects us to provide a class type. The Injector creates a new instance from the type and injects it. 

The useClass provider key lets you create and return new instance of the specified class. You can use this type of provider to substitute an alternative implementation for a common or default class.

If you specify the service class as the provider token, the default behavior is for the injector to instantiate that class using the new operator. It is similar to calling the new operator and returning the instance. If the type requires any constructor parameters, the injector will resolve that too.

providers :[{ provide: UserService, useClass: UserService }]

In the above, example the provide i.e. UserService is the Token (or key) and it maps to the UserService Class. Here in this case both the Class name and token name match. In fact, the class provider syntax is a shorthand expression that expands into a provider configuration, defined by the Provider interface. So Angular Provides a shortcut way as well in cases where both token & class name must match as follows: 

providers: [UserService]

You can also provide a mock/Fake class for Testing purposes as shown below.

 providers :[{ provide: UserService, useClass: fakeUserService }]

Q186. What is a Value Provider in Angular DI System? What is the difference between Value Provider vs. Factory Provider in Angular?

Value Provider (useValue):

We use the Value Provider i.e. useValue, when you want to provide a simple primitive value. The Angular will inject whatever value is provided in the useValue as it is. It is useful in scenarios like, where you want to provide API URL, application-wide configuration Options, etc.

 providers :[ {provide:'USE_DBLog', useValue: true}]

You can also pass an object. You can also use the Object.freeze to freeze the value of the object configuration, so that nobody can change it.

Value Provider vs Factory Providers:

The value Provider i.e. useValue returns the function as it is. 

providers: [
    {
      provide: 'FUNC',
      useValue: () => {
      return 'welcome';
      }
    }
    ]

You need to call this function i.e. someFunc() to get the value.

export class AppComponent {
  constructor(
  @Inject('FUNC') public someFunc: any
  ) {
  console.log(someFunc());
  }
}

You can achieve the same with the useFactory as well. The useFactory invokes the factory function and returns the result.

providers: [
    {
      provide: 'FUNC',
      useFactory: () => {
      return 'welcome';
      }
    }
    ]

Hence in the component when you use this, you will receive the value of the function and not the function itself like we got in the case of value provider.

Q187. What is Factory Provider in Angular DI System? What is the use of deps array in the Factory Provider of Angular?

Factory Provider (useFactory):

The useFactory provider key lets you create a dependency object by calling a factory function. With this approach, you can create a dynamic value based on information available in the DI and elsewhere in the app.

The Factory Provider i.e. useFactory expects us to provide a function. It invokes the function and injects the returned value. We can also add optional arguments to the factory function using the deps array. The deps array specifies how to inject the arguments. We usually use the useFactory when we want to return an object based on a certain condition.

Consider the scenario where we want to inject either UserService or FakeUserService based on the value for USE_FAKE. Also, one of the services (UserService ) requires another service (LoggerService). Hence we need to inject USE_FAKE & LoggerService into our factory function.

  providers: [
    { provide: LoggerService, useClass: LoggerService },  
    { provide: 'USE_FAKE', useValue: true },  
    {
      provide: UserService,
      useFactory: (USE_FAKE, LoggerService) =>
      USE_FAKE ? new FakeUserService() : new UserService(LoggerService),
      deps: ['USE_FAKE', LoggerService]
    }
    ]

We need to pass all the dependencies of the service as the argument to the factory function. 

The factory function has access to UserService. You inject both Logger and UserService into the factory provider so the injector can pass them along to the factory function. 

Here the useFactory field specifies that the provider is a factory function whose implementation is UserService or FakeUserService. 

The deps property is an array of provider tokens. The Logger and UserService classes serve as tokens for their own class providers. The injector uses the deps array to resolve the dependencies and inject them. 

The injector resolves these tokens and injects the corresponding services into the matching UserService factory function parameters. Here inside the factory function, we either return FakeProductService or ProductService depending on the value of USE_FAKE.

In the last option, we need to tell the Injector how to inject the dependencies of the Factory function itself. Note that the order must be the same as that of the factory function argument.

Q188. What is an Aliased Provider in Angular DI System? What is the difference between useExisting vs. useClass in Angular?

Aliased Provider (useExisting):

We use Aliased Provider i.e. useExisting when we want to use the new provider in place of the old Provider. The useExisting provider key lets you map one token to another. In effect, the first token is an alias for the service associated with the second token, creating two ways to access the same service object.

providers: [
    { provide: LoggerService, useClass: LoggerService },
    { provide: OldLogger, useExisting: LoggerService },
  ]

Or in short:

providers: [
    LoggerService,
    { provide: OldLogger, useExisting: LoggerService },
  ]

In the above example, we map the OldLogger to the LoggerService token using useExisting Provider. The injector injects the singleton instance of LoggerService when the component asks for either the new or the old logger. In this way, OldLogger is an alias for NewLogger.

NOTE: Please make sure that you do not alias OldLogger to LoggerService with useClass, as this creates two different LoggerService instances.

Also, note that we need to pass the token to the useExisting and not type. The following example shows useExisting with string tokens.

  providers: [
    { provide: UserService, useExisting: 'USER_SERVICE' },
    { provide: 'USER_SERVICE', useClass: NewUserService },
  ]


Q189. Can you add multiple providers for the same DI token in Angular?  How can you use multiple providers with the same token in Angular?

Yes, You can add as many dependencies to the Providers array. The Injector does not complain if you add more than one provider with the same token.

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  providers :[
    { provide: UserService, useClass: UserService },
    { provide: UserService, useClass: AdminUserService }
  ]
})
export class UserModule{ }

In such a scenario, the service which is registered at last always wins. So here in the above example UserService token always injects AdminUserService because we register it last.

Registering the Dependency at Multiple Providers:

Similarly, you can register a Dependency with Multiple Providers as well. For example, you can register a dependency in the NgModule along with a component.

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  providers :[
    { provide: UserService, useClass: UserService }  
  ]
})
export class UserModule{ }

We can also go and register it in AppComponent. In this case, AppComponent always gets the dependency registered in the component itself.

@Component({
  selector: 'app-user-component',
  templateUrl: './user-component.component.html',
  styleUrls: ['./user-component.component.scss'],  
  providers :[
    { provide: UserService, useClass: UserService }  
  ]
})

Where you register the dependency, it defines the lifetime of the dependency. When you provide the service in the @ngModule of the root module or any eagerly loaded module, it will be available everywhere in the application.

But if we provide the services in the @Component, @pipe, or @Directive then they are available only in that component and all of its child components. The services provided in the @ngModule of the lazy loaded module are available in that module only.

Q190. What is the difference between multi-provider and regular provider in Angular?

A provider is an instruction that describes how an object for a certain token is created. In Angular, a provider is a way to create a service. When you register a provider with an injector, the injector creates an instance of that service when it is requested by anyone. A token can be either a string or a type.

regular provider is a provider that is registered with an injector using a token. When you inject a service into a component or other service, Angular looks up the token in the injector and creates an instance of the service if it has not already been created.

The new dependency injection system of Angular comes with a feature called “Multi Providers”.  Using multi: true tells Angular that the provider is a multi-provider and one provider token provides an array of elements. 

A multi-provider is a provider that allows you to register multiple providers for the same token. With the multi-providers, we can basically provide multiple dependencies for a single token in the DI.

Here we have two providers, both have the same token but they provide different values. If we ask for a dependency for that token, what we get is a list of all registered and provided values.

This is useful when you want to provide multiple implementations of the same service. When you inject a multi-provider into your component or other service, Angular returns an array of all the instances of the service that have been registered with the injector. Usually, when we register multiple providers with the same token the last one wins.

With multiple providers, we can basically extend the thing that is being injected for a particular token. Angular uses this mechanism to provide pluggable hooks. This is used mostly in those scenarios where we use primitives or chunks of values. Generally, we do not use it in injecting the array of classes, but there are some use cases in the framework where we do.

Q191. What is the difference between StaticProvider vs. Provider in Angular?

In Angular, both Provider, and StaticProvider are used to register a service provider, but they have different behaviors.

The Provider class is used to register a provider at the module level. When you add a provider to the providers array in a module, it becomes available throughout the entire application. 

On the other hand, StaticProvider is used to configure an injector as static, which means that it does not use reflection. A static provider provides tokens to an injector for various types of dependencies.

There are two types of providers in Angular: StaticProvider and Provider

Provider:

It is a provider that we usually use when registering providers in @NgModule,  @Component, or @Directive metadata. Here the"deps" is not required to register the services. We only need to provide Params in the Providers array and angular will do all the job for us.

StaticProvider:

Static providers are a special type of provider that is used to configure Injectors in a static way (without Reflection). It was introduced with Angular 5.  

StaticProvider describes how an Injector should be configured as static. A static provider provides tokens to an injector for various types of dependencies.

type StaticProvider = ValueProvider | ExistingProvider | StaticClassProvider | ConstructorProvider | FactoryProvider | any[];

For example, when we pass a provider to a platform we have to specify deps because we have to use StaticClassProvider or ConstructorProvider instead of just ClassProvider. When we create Injector dynamically we have to specify "deps" because Injector takes StaticProvider array.

const platform = platformBrowserDynamic([ {
  provide: SharedService,
  deps:[]
}]);
platform.bootstrapModule(AppModule);

The "deps" are available only in useFactory providers but not in useClass providers. Both class provider parameters and factory provider deps accept an array consisting of provider tokens or arrays of decorator instances.

provider-vs-staticprovider
Source: StackOverflow


Provider vs. StaticProviders:

The main difference between Provider and StaticProvider is that Provider is used for dynamic injection, while StaticProvider is used for static injection

In dynamic injection, the injector uses reflection to determine the dependencies of a component or service at runtime. In contrast, static injection uses a configuration file to specify the dependencies of a component or service at compile time.

Q192. What is the difference between the providers array vs. deps array for registering services in Angular?

We register all dependencies of the application with the Providers. In Angular, the providers array is used to register a provider for a dependency. A provider can be a class, a value, or a factory function. When a provider is registered in the providers array of a component, it becomes available to that component and all its child components. 

The deps array, on the other hand, is used to specify the dependencies of a factory functionIn Angular, deps is an array of provider tokens that are used to specify the dependencies of a factory function. The deps array is used when a factory method needs the injected tokens. 

deps : any[]  It is a list of tokens that need to be resolved by the injector. The list of values is then used as arguments to the useFactory function. The deps property is an array of provider tokens. The injector resolves these tokens and injects the corresponding services into the matching service factory function parameters.

This is a way to tell Angular DI what dependencies it needs to inject into the factory function returned by runnersUpFactory. For services, there is the @Injectable class to tell DI that it needs to analyze the constructor parameter of this class (same for @Component(), @Directive(), and @Pipe()), but this seems not to work for functions. Therefore they introduced the deps parameter.  Therefore they introduced the deps parameter. These Dependencies can also be marked as optional: 

deps: [[new Optional(), Location]]

The deps array is only relevant when useFactory is used. However, it can also be used with useClass when injecting generic dependencies that require explicitly named tokens. 

If we use useClass to provide an instance of Foo, the dependencies will be injected into the constructor parameters. The deps array would be appended to the constructor parameters if they already exist.

export const userServiceProvider =
  { provide: UserService,
    useFactory: userServiceFactory,
    deps: [Logger, UserService]
  };

In summary, the providers array is used to register providers for dependencies while the deps array is used to specify dependencies of a factory function.

Q193. What is the difference between the Providers Array and viewProviders Array in Angular?

When you provide/register services in any component class, those services are visible only within the ElementInjector tree relative to where and how you provide those services. How you provide services using a @Component() or @Directive() decorator determines their visibility.

The viewProviders are similar to Providers except that the dependencies that you define are visible only to its view children. They are not visible to the Content children.  The ViewProviders defines the set of injectable services that are visible only to its view DOM children. These services are not visible to views projected via content projection. The viewProviders is useful when you develop libraries.

ViewProviders vs Providers:

The providers are used to register a service provider at the module level. When you add a service provider to the providers array, it becomes available throughout the entire application.

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  providers :[
    { provide: UserService, useClass: UserService }  
  ]
})
export class UserModule{ }

On the other hand, viewProviders is used to register a service provider at the component level. When you add a service provider to the viewProviders array, it becomes available only to that component and its children. However, we can use both providers and viewProvider in a component.

@Component({
  selector: 'app-user-component',
  templateUrl: './user-component.component.html',
  styleUrls: ['./user-component.component.scss'],  
  viewProviders :[
    { provide: UserService, useClass: UserService }  
  ]
})

The services declared in Components Providers are injected to both view children and content children. But the services declared in viewProviders are injected only to view Children. ViewProviders metadata is available only to Angular Components. Providers are available in ngModuleComponentPipesDirectives, etc.

@Component({
  selector: 'app-user-component',
  templateUrl: './user-component.component.html',
  styleUrls: ['./user-component.component.scss'],  
  providers :[
    { provide: UserService, useClass: UserService }
  ],
  viewProviders :[
    { provide: LogService, useClass: LogService }  
  ]
})




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.