Angular Typescript依赖注入公共与私有

Angular Typescript依赖注入公共与私有,angular,typescript,Angular,Typescript,使用public和private注入服务的区别是什么。我看到大多数示例在angular组件中使用private关键字。使用公共服务会有什么影响吗? e、 g vs 答案很简单:当您不需要在当前类/组件之外使用私有变量时,您必须创建私有变量,否则,您应该创建公共变量。还有一件事:您还可以使用私有变量,并通过名为getters和setters的特殊函数从外部访问它们。例如: private _customValue: any; set customValue(newValue: any): voi

使用public和private注入服务的区别是什么。我看到大多数示例在angular组件中使用private关键字。使用公共服务会有什么影响吗? e、 g

vs


答案很简单:当您不需要在当前类/组件之外使用私有变量时,您必须创建私有变量,否则,您应该创建公共变量。还有一件事:您还可以使用私有变量,并通过名为getterssetters的特殊函数从外部访问它们。例如:

private _customValue: any;

set customValue(newValue: any): void {
  this._customValue = newValue;
}

get customValue(): any {
  return this._customValue;
}
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class CarService {

  constructor() { }

  public design = {
    "color": "blue"
  }
}
请注意,
\u customValue
是私有的,但是您可以通过使用
customValue
的操作从类外设置/获取此值:

classInstance.customValue = 'newValue';
console.log(classInstance.customValue);

需要说明的是,在方法名称之前的
set
get
关键字不是很需要,它们更需要澄清。

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

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

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

大概是这样的:

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

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

对于您拥有服务的情况,例如:

private _customValue: any;

set customValue(newValue: any): void {
  this._customValue = newValue;
}

get customValue(): any {
  return this._customValue;
}
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class CarService {

  constructor() { }

  public design = {
    "color": "blue"
  }
}
在您的构造函数中,您将在其中实现服务

constructor(private carService: CarService) { }
 getCarService() {
      return this.carService;
 }
您可以使用普通方法返回服务

constructor(private carService: CarService) { }
 getCarService() {
      return this.carService;
 }
在模板中,您可以执行以下操作

<div>{{getCarService().design.color}}</div>
{{getCarService().design.color}

我尝试在您设置“get-isValid():boolean{..}时使用语法,但至少在我的设置中isValid():boolean{…}对函数签名有效。上面是一个getter。您不会像调用方法一样调用它,而是将其作为属性赋值。如果您使用
*ngIf='isValid'
而不是
*ngIf='isValid(),它应该会起作用“
getter也是如此。您能指出文档来支持您的说法吗“最佳做法是将任何服务属性/方法包装在组件属性/方法中,并将模板绑定到/调用组件的属性或方法?”"? 听起来好像有很多不必要的工作。为什么不将服务
公开为只读
,以防止将来的开发人员在编译时使用它,并避免编写所有额外的样板文件呢?这是向GDE社区提出的。。。多重思想。(1) 使用编辑器工具进行的任何重构(重命名等)都不会在模板中找到实例。(2) 使用推荐的视图/模型方法和声明的可观察流,这就不是问题了。(3) 对于一次性,似乎可以。您不调用getter和setter,使用此代码您创建了一个名为
getCustomValue
的只读属性和一个名为
setCustomValue
的不相关的只写属性。它们都应命名为
customValue
,并被视为property@WilliamLohan,同意,更合适的方法是使用
customValue
name,但功能是否有问题?