Narayan Prusty
Narayan Prusty

Reputation: 2581

Difference between ViewProviders and Services in Angular2?

Consider this code:

var SearchResultComponent = ng.core.Component({
    selector: "search-result",
    directives: [ng.router.ROUTER_DIRECTIVES, FormComponent],
    viewProviders: [ng.http.HTTP_PROVIDERS],
    templateUrl: "componentTemplates/SearchResult.html"
}).Class({
    constructor: [ng.http.Http, function( http) {
        this.http = http;
    }],
    ngOnInit: function(){
    }
})

Here we provided viewProviders ng.http.HTTP_PROVIDERS and the service we injected is ng.http.Http. So what's the difference between them. Why do we need ViewProviders.

Upvotes: 2

Views: 2461

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657741

Providers are used by Angular's dependency injection (DI) to resolve dependencies.

Providers and services are not "either or", but "as well as"

If your component or service has a dependency (like ng.http.Http, in your example), DI looks up the providers tree and returns an instance from the first provider it finds.

If the providers or viewProviders of your component doesn't have a provider for the requested type or token registered, DI checks the parent components providers up to the providers provided by bootstrap(...).

What instance your component or service gets passed to the constructor depends on where the provider for this dependency is registered.

If component B and the parent component A have a provider for a specific service registered, then B gets an instance from B. If C, a sibling component of B, also has a dependency on this service but doesn't have a provider registered itself, it gets a service instance of A.

This way you can define the scope of service instances.

Upvotes: 2

Related Questions