Angular Service中的布尔值未按预期工作

问题描述 投票:0回答:1

基本上,我的服务中有一个布尔canSiteReload,它基于同一服务中的另一个布尔hasChanges

服务看起来像这样:

@Injectable({
  providedIn: 'root'
})
export class ApplicationService {

  constructor() { }

  public hasChanges: boolean = false;
  public canSiteReload: boolean = this.hasChanges === false;
}

问题是,当我将hasChanges更改为true时,即使canSiteReload应该返回this.hasChanges === false,因为false现在为true,hasChanges仍将返回true。

为什么会发生这种情况,如何根据canSiteReload来确定hasChanges的值?如果可能的话,我想避免额外的代码,例如没有功能/设置程序。

复制者:https://stackblitz.com/edit/angular-rwcza8

angular typescript angular-services
1个回答
0
投票

同意@David的评论。没有编写功能,canSiteReload似乎没有更新。

我分叉并更改了以下部分:

this.appService.hasChanges = false;

我在服务中创建了一个函数,并使用该函数更新了值。像这样:

public change(): void{
  this.appService.saveChanges(true);
  console.log('Has changes?: ', this.appService.hasChanges);
  console.log('Can site reload?: ', this.appService.canSiteReload);
}

public undo(): void{
  this.appService.saveChanges(false);
  console.log('Has changes?: ', this.appService.hasChanges);
  console.log('Can site reload?: ', this.appService.canSiteReload);
}

我认为它正在运行。

分叉:https://stackblitz.com/edit/angular-aeyxgg

© www.soinside.com 2019 - 2024. All rights reserved.