本文介绍了Angular中的视图提供者是什么?黑白提供者与视图提供者有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码中的viewProviders是什么?以及它与提供者有何不同?

What is viewProviders in the below code? And how it differs from providers?

class Greeter {
   greet(name:string) {
     return 'Hello ' + name + '!';
   }
}
@Component({
  selector: 'greet',
  viewProviders: [
    Greeter
  ],
  template: `<needs-greeter></needs-greeter>`
})
class HelloWorld {
}

推荐答案

在您的示例中,提供者和viewProvider之间没有区别,因为HelloWorld的模板不使用<ng-content>.如果您要在<ng-content>...</ng-content>中投影内容,则因为正在使用

In your example, there is no difference between providers and viewProviders because HelloWorld's template doesn't use <ng-content>. If you were projecting content within <ng-content>...</ng-content>, then Greeter couldn't be injected in the projected content because you're using

viewProviders: [Greeter]

如果您希望将Greeter潜在地注入到投影内容中,则可以使用

If you wanted Greeter to potentially be injected into the projected content, you'd use

providers: [Greeter]

因此,viewProviders将提供者限制为非计划内容的子对象,而providers允许所有子代使用提供者.值是viewProviders允许您防止投影的内容与您的服务混乱,这在库中尤其有用.

So viewProviders limits the provider to children other than projected content, while providers allows all children to use the provider. The value is that viewProviders allows you to prevent projected content from messing with your services, which could be especially useful in libraries.

这篇关于Angular中的视图提供者是什么?黑白提供者与视图提供者有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 10:17