【问题标题】:Is it good practice to reference services in html templates in Angular 2?在 Angular 2 的 html 模板中引用服务是一种好习惯吗?
【发布时间】:2016-08-24 19:34:00
【问题描述】:

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

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

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

示例:我想通过更改“stateService”中的“currentStep”从 step1 移动到 step2,但是我希望将“currentStep”保持为局部变量的组件也反映状态的变化?

【问题讨论】:

  • 我会避免它。如果组件多次访问一个值怎么办?

标签: templates service angular state observable


【解决方案1】:

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

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

缺点:

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

优点:

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

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

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;
  });
}

【讨论】:

【解决方案2】:

你可以试试下面,

状态服务

 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;
    });
 }

希望这会有所帮助!

【讨论】:

    【解决方案3】:

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

    状态服务

    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
    

    【讨论】:

      猜你喜欢
      • 2019-03-06
      • 1970-01-01
      • 2022-01-23
      • 2020-06-04
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多