[Angular] 'providedIn' for service
There is now a new, recommended, way to register a provider, directly inside the @Injectable()
decorator, using the new providedIn
attribute.
@Injectable({ providedIn: 'root' }) export class UserService { }
When you use 'root'
, your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule
, the injectable is registered as a provider of the UsersModule
without adding it to the providers of the module.
In the same spirit, you can now declare an InjectionToken
and directly register it with providedIn
and give it a factory
:
export const baseUrl = new InjectionToken<string>('baseUrl', { providedIn: 'root', factory: () => 'http://localhost:8080/' });
Note that it also simplifies unit testing. We used to register the service in the providers of the testing module to be able to test it.
Before:
beforeEach(() => TestBed.configureTestingModule({
providers: [UserService]
}));
Now, if the UserService
uses providedIn: 'root'
:
After:
beforeEach(() => TestBed.configureTestingModule({}));