Question 1:
What should the whole class look like? Where should the above code segments be added?
Answer:
You can create a file containing the code for the hero service provider and its factory function. This file may be called hero.service.provider.ts .
And write the hero service code in another file called hero.service.ts .
Check out this article on how to use Angular service providers to see more examples.
File hero.service.provider.ts :
import { HeroService } from './hero.service'; import { Logger } from './logger.service'; import { UserService } from './user.service'; let heroServiceFactory = (logger: Logger, userService: UserService) => { return new HeroService(logger, userService.user.isAuthorized); }; export let heroServiceProvider = { provide: HeroService, useFactory: heroServiceFactory, deps: [Logger, UserService] };
Question 2: How / can I use this factory?
Answer:
According to the sample code you provided, the factory can be configured for the service using the provider field in the @Component decorator, and the service can be implemented through the class constructor or using the angular injection object.
However, shaking the tree does not work when the factory provider configured this path. Check out this example angular tree swing service if you need the tree to work.
import { heroServiceProvider } from './hero.service.provider'; import { HeroService } from './hero.service'; @Component({ selector: 'my-selector', template: '', providers: [heroServiceProvider] }) export class HeroComponent { constructor(private heroService: HeroService) { } }
source share