Several dependency injection methods of angular

Keywords: angular

1,useClass

One way to write a provider is like this

providers: [...Service...],

Its complete writing method is

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

provide provides the token and the service actually used is the service declared by useClass, as follows

providers: [{provide:Service,useClass:anotherService}],

If otherservice needs to implement other classes, the methods in the class should be implemented as follows: otherservice implements Service

Class Service

import { Injectable } from '@angular/core';

@Injectable()
export class ServiceService {

  constructor() { }
  methods(){
    console.log('The first service class')
  }
}

Otherservice class

import { Injectable } from '@angular/core';
import {ServiceService} from './service.service';

@Injectable()
export class AnotherServiceService implements ServiceService{

  constructor() { }
  methods(){
    console.log('Another service class')
  }
  anotherMethods(){
    console.log('Another service class')
  }

}

At the same time, services can also use each other, provided the @ Injectable() decorator is added,
Use to inject services into the constructor as in the component.

2, value

The token of its provider is a string, using useValue, which can be an object or a value

providers: [{provide:'IS_Value',useValue:false}],

Note that there are slightly different ways to get data in components. Data is the obtained value

 constructor(@Inject('IS_Value') private data) { }

3. Factory method definition provider

Factory methods will only be called once, as follows

provides:[
		{
		provide:ServiceService,
		useFactory:()=>{
			     let dev=Math.random()>0.5
			       if(dev){
			       return new ServiceService()
			       }else {
			       return new AnotherServiceService()
			       }
			  }
		 }
    ]

If the factory function wants to use the provider's other services to join the property deps and pass it in as a parameter

provides:[
	loggerService,
		{
		provide:ServiceService,
		useFactory:(logger:loggerService)=>{
			     let dev=Math.random()>0.5
			       if(dev){
			       return new ServiceService(logger)
			       }else {
			       return new AnotherServiceService(logger)
			       }
			  }
			  deps:[loggerService]
		 }
    ]

This is equivalent to instantiating loggerService, but the condition is not simple. We can also pass in a value through a random number

provides:[
	loggerService,
	{provide:'IS_Value',useValue:false}
		{
		provide:ServiceService,
		useFactory:(logger:loggerService,val)=>{
			     let dev=Math.random()>0.5
			       if(dev){
			       return new ServiceService(logger)
			       }else {
			       return new AnotherServiceService(logger)
			       }
			  }
			  deps:[loggerService,'IS_Value']
		 }
    ]

The factory function then searches for the second value of deps and passes it to the second parameter

Posted by kimbeejo on Mon, 30 Dec 2019 06:24:27 -0800