Angular2 中 ViewProvider 和服务的区别?

Difference between ViewProviders and Services in Angular2?

考虑这段代码:

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(){
    }
})

这里我们提供了viewProvidersng.http.HTTP_PROVIDERS,我们注入的服务是ng.http.Http。那么它们之间有什么区别呢。为什么我们需要 ViewProvider。

Angular 的依赖注入 (DI) 使用提供程序来解决依赖关系。

提供商和服务不是 "either or",而是 "as well as"

如果您的组件或服务具有依赖项(例如 ng.http.Http,在您的示例中),DI 将查找提供者树和 returns 它找到的第一个提供者的实例。

如果您的组件的 providersviewProviders 没有注册请求类型或令牌的提供者,DI 将检查父组件提供者直到 [=13] 提供的提供者=].

您的组件或服务传递给构造函数的实例取决于此依赖项的提供程序在何处注册。

如果组件 B 父组件 A 注册了特定服务的提供程序,则 B 从 B 获取实例。如果 C 是 B 的兄弟组件,也依赖于此服务但没有注册自己的提供者,它获得 A 的服务实例。

这样您就可以定义服务实例的范围。