Do Angular useExisting providers create a new object of service?

Short answer is NO, the useExisting provider use object created by other tokens. Read on,

To learn more about such concepts, join a free webinar on Saturday, 20 June 4 PM IST. RSVP here:

https://www.meetup.com/Geek97/events/271292371/

In Angular, providers determine how an object of a particular token gets created. That means whether Angular creates a new object, use an existing object, or use a value etc.

Angular has four types of providers options, they are

  1. useClass
  2. useExisting
  3. useFactory
  4. useValue

Among these four types, the useExisting option uses the object of an existing token. That means it does not create a new object.  To understand it in a better way, let us create two classes


  class Greeting {
    title = 'Hello';
  }
  
  class FormalGreeting extends Greeting {
    title = 'Greetings';
  }


Next, create injectors to inject dependencies of these classes.


  // Creating Injecting

  const injector = Injector.create([
    {provide: FormalGreeting,useClass:FormalGreeting,deps: []}, 
    {provide: Greeting, useExisting: FormalGreeting}
  ]);

As you see for the Greeting token, Injector uses the existing token of FormalGreeting using the useExisting provider option.  

Since the useExisting option is used, Angular won’t create a new object for Greeting token and use the existing object of FormalGreeting token.

You can verify that using the below unit test.


  // Unit Test
 
  it('should use the existing object for Greeeting token', () => {
    expect(injector.get(Greeting).title).toEqual('Greetings');
    expect(injector.get(FormalGreeting).title).toEqual('Greetings');
    expect(injector.get(FormalGreeting)).toBe(injector.get(Greeting));
  });

On running the test, you should get a test passed.

Now if you change the injector to use the useClass option as shown below,


  const injector = Injector.create([
    {provide: FormalGreeting,useClass:FormalGreeting,deps: []}, 
    {provide: Greeting, useClass: Greeting}
  ]);


And run the test again, you get a failed test because Angular is creating a new object for Greeting token as we are using the useClass provider.

So, in summary, the Angular use existing object instead of creating a new object in the useExisting option.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s