Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use factory provider?

I need to inject a service into another service in an Angular 2 application.

After reading the docs I deduced, that the best approach is to use a Factory Provider. However, two questions have arisen:

1) The docs recommend the creation of a HeroServiceProvider class with two "code segments":

let heroServiceFactory = (logger: Logger, userService: UserService) => {
  return new HeroService(logger, userService.user.isAuthorized);
};

export let heroServiceProvider =
  { provide: HeroService,
    useFactory: heroServiceFactory,
    deps: [Logger, UserService]
  };

My question is how should the class generally look like? Where should one add the above code segments?

2) How should/could one use this factory? I see, it should be imported as:

import { heroServiceProvider } from './hero.service.provider';

@Component({
  selector: 'my-selector',
  template: `
  `,
  providers: [heroServiceProvider]
})

How could then the desired parametrized service retrieved and accessed?

like image 646
arjacsoh Avatar asked Oct 01 '16 06:10

arjacsoh


People also ask

When would you use the use factory provide method?

To summarize, choose useValue to provide the same injected value each time*, useFactory when the injection value should be computed at runtime, and useClass when you want the injector to construct a value of Type<any> to provide.

What is factory provider?

The first argument of the Factory provider is a class, a factory function or a method that creates an object. The rest of the Factory positional and keyword arguments are the dependencies. Factory injects the dependencies every time when creates a new object.

What is factory provider in Angular?

A provider is basically an object that tells Angular injector how to obtain or create a dependency. When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the constructor parameter types.

What is the use of useFactory in Angular?

The useFactory field tells Angular that the provider is a factory function whose implementation is heroServiceFactory . The deps property is an array of provider tokens. The Logger and UserService classes serve as tokens for their own class providers.


1 Answers

I faced same issues to inject on app_initalizer, after long search i found the solution below. May be this is help for your scenario.

@NgModule({
  imports: [ BrowserModule],
  ...
  providers: [
    {
      provide: HeroService,
      useFactory: heroServiceFactory,
      deps: [Logger, UserService],
      multi: true
    }
    ]
})
export class AppModule {}


export function heroServiceFactory = (logger: Logger, userService: UserService) => {
    return new HeroService(logger, userService.user.isAuthorized);
};
like image 100
Rajamohan Anguchamy Avatar answered Oct 11 '22 04:10

Rajamohan Anguchamy