打字稿依赖注入public

打字稿依赖注入public

本文介绍了打字稿依赖注入public vs private的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用public和private注入服务有什么区别.我看到大多数示例在angular组件中使用private关键字.使用public有什么影响吗?例如

What is the difference between injecting service with public and private.I see most of examples use private keyword in angular component. Would it have any implications of using public?e.g.

constructor(public carService: CarService) { }

vs.

constructor(private carService: CarService) { }

推荐答案

除了先前的答案外,组件模板也无法访问任何标记为私有的内容. (使用JIT时(例如在开发时,可以访问私有成员 ,但是在使用AOT时(例如用于生产时)则不能访问.)

In addition to the prior answer ... anything marked as private cannot be accessed by the component's template either. (Private members can be accessed when using JIT, such as at development time, but not when using AOT, such as for production.)

因此,在您的模板中,您只能执行*ngIf='carService.isValid'如果已将注入的服务标记为public.

So in your template, you could only do *ngIf='carService.isValid'if the injected service was marked as public.

但是实际上,最佳实践是将任何服务属性/方法都包装在组件属性/方法中,并使模板绑定到/调用组件的属性或方法.

But actually, best practice is to wrap any service properties/methods in a component property/method anyway and have the template bind to/call the component's property or method.

类似这样的东西:

   get isValid(): boolean {
      return this.carService.isValid;
   }

然后像这样访问它:*ngIf='isValid'

这篇关于打字稿依赖注入public vs private的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:14