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”的组件也作为局部变量来反映状态的变化吗?
在Angular 2的html模板中引用服务是否是一种好习惯?
我通常会避免它。看来带来的混乱多于好处。
缺点:
Component)在视图和服务之间起中介作用。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)
| 归档时间: |
|
| 查看次数: |
1847 次 |
| 最近记录: |