在Angular 2的html模板中引用服务是否是一种好习惯?

Zer*_*ool 5 service templates state observable angular

正如问题所指出的那样,直接在模板中这样引用服务是否有任何弊端:

 [disabled]="stateService.selectedClient == null || stateService.currentStep == 1"
Run Code Online (Sandbox Code Playgroud)

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

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

Har*_*inh 5

在Angular 2的html模板中引用服务是否是一种好习惯?

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

缺点:

  • 从OOP的背景来看,这种方法似乎违反了Demeter定律,但更重要的是,
  • 它不再是MVC,您的控制器(Angular2的Component)在视图和服务之间起中介作用。
  • 就像Ced所说的,如果对服务成员的调用成本很高,而我们需要在视图中多次引用它,该怎么办?
  • 目前,我选择的编辑器(VS Code)不完全支持Angular2模板;Component在一个template重构中引用太多超出其自身范围的东西使重构变得不再有趣。

优点:

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

在观察变化的同时,如何获取状态并将其存储到局部变量中

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);
}
Run Code Online (Sandbox Code Playgroud)

在您的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;
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 与普遍的看法相反,角度建议直接从模板绑定到您的服务。请阅读此处:https://angular.io/tutorial/toh-pt4#bind-to-the-messageservice 再说一次,我自己不喜欢那样,感觉像是一种反模式。 (6认同)