How to introduce a provider to an Angular 2 service from an action?

I am trying to remove component dependency on services in Angular using Redux.

Basically, the flow Component β†’ Action β†’ Service

In the service, I want to use the @ angular / core http module, which is proposed to be passed in the constructor:

export class SampleService {
    constructor(public http: Http) {}
}

And since I call the service from the action, it will not get the http provider, since I do not have an instance of the http provider.

export default class SampleAction {
    private _projectService;
    constructor() {
        this._sampleService = new SampleService();
    }
}

How can I enter the http provider into the service?

+4
source share
3 answers

In your action, you can inject the Http constructor into the constructor and pass it to the service instance. Sort of

export default class SampleAction {
    private _projectService;
    constructor(@Inject(Http) http: Http) {
        this._sampleService = new SampleService(http);
    }    
}
+2
source

. . , . Http ( HTTP_PROVIDERS) SampleSampleService. ( ) (providers).

bootstrap(AppComponent, [ HTTP_PROVIDERS, SampleService ]);

@Component({
  providers: [ HTTP_PROVIDERS, SampleService ]
})
export class SomeComponent {
  constructor(private action: SampleAction) {
  }

  executeAction() {
    this.action.doSomething();
  }
}

, SampleAction:

export default class SampleAction {
  constructor(private _projectService: SampleService) {
  }
}

, @Injectable.

@Injectable()
export class SampleService {
  constructor(public http: Http) {}
}

, Angular2:

0

new SomeService().

Instead, simply add classes to the providers bootstrap(.., [Providers])or to the component, which should be the root of the scope in which the shared service instance should be used.

Also add all the dependencies (constructor arguments) to the list of providers.

If everything is configured correctly, wherever the instance is requested by the constructor argument, an instance with automatically resolved dependencies is passed.

Just set up DI and give it a job for you.

0
source

Source: https://habr.com/ru/post/1628843/


All Articles