在 Angular 2 的 html 模板中引用服务是好的做法吗?

Is it good practice to reference services in html templates in Angular 2?

如问题所述,直接在模板中引用服务是否有任何缺点:

 [disabled]="stateService.selectedClient == null || stateService.currentStep == 1"

在我看来,这似乎不是一个好的做法,我更愿意在任何需要使用它的组件中保留一个 "selectedClient" 对象。如何获取状态并将其存储到局部变量中,同时观察变化:

示例:我想通过更改 "stateService" 中的 "currentStep" 从第 1 步移动到第 2 步,但是我希望保留 "currentStep" 的组件也作为局部变量来反映状态有变化?

你可以试试下面,

stateService

 currentStep : Subject<number> = new Subject<number>();

 somestepChangeMethod(){          
    this.currentStep.next(<set step here to depending on your logic>);
 }

组件

 // use this in template
 currentStep: number;

 constructor(stateService : stateServiceClass){
    stateService.currentStep.subscribe(val => {
       this.currentStep = val;
    });
 }

希望对您有所帮助!!

Is it good practice to reference services in html templates in Angular 2?

我通常会避免它。似乎带来的混乱多于好处。

缺点:

  • 来自 OOP 背景,这种方法看起来打破了 Law of Demeter,但更重要的是,
  • 它不再是 MVC,您的控制器(Angular2 的 Component)充当视图和服务之间的中介。
  • 就像Ced说的,如果调用一个服务的成员是昂贵的,我们需要在视图中多次引用它怎么办?
  • 目前我选择的编辑器 (VS Code) 不完全支持 Angular2 模板;在 template 中引用太多超出自身 Component 范围的东西使得重构不再有趣。

优点:

  • 有时它看起来更优雅(因为它为您节省了 2 行代码),但相信我,事实并非如此。

How can I get the state and store it into local variables, while observing the changes

Madhu Ranjan 对此有很好的回答。对于您的特定示例,我将尝试在此处使其更加完整:

在你的StateService中定义:

currentStep : Subject<number> = new Subject<number>();
selectedClient: Subject<Client> = new Subject<Client>();

changeStep(nextStep: number){          
  this.currentStep.next(nextStep);
}

selectClient(client: Client) {
  this.selectedClient.next(client);
}

在你的Component中:

currentStep: number;

constructor(stateService : StateService){
  stateService.currentStep.combineLatest(
    stateService.selectedClient, 
    (currStep, client) => {
      if (client == null) {
        // I'm assuming you are not showing any step here, replace it with your logic
        return -1; 
      }
      return currStep;
    })
  .subscribe(val => {
    this.currentStep = val;
  });
}

在状态服务中公开您的主题可能不是一个好主意。像这样就更好了。

StateService

private currentStep: Subject<number> = new Subject<number>();

changeStep(value: number) {
  this.currentStep.next(value);
}

get theCurrentStep(): Observable<number> {
  this.currentStep.asObservable();
}

组件

currentStep: number;

constructor(private stateService: StateService) {
  this.currentStep = this.stateService.theCurrentStep;
}

模板

[disabled]="(currentStep | async) == 1" // Not sure if this part would work