无法从服务检索 Angular 信号

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

我正在尝试使用服务将选定的划分对象放入服务中,然后以详细信息形式检索它。该服务的代码是:

 private currentDivision = signal<Division>(new Division(), undefined);

  setCurrentDivision(division: Division): void {
    this.currentDivision.set(division);
    console.log(this.currentDivision());
  }
  getCurrentDivision(): Division {
    console.log(this.currentDivision());
    return this.currentDivision();
  }

列表的代码是

onSelect(division: Division): void {
    this._divisionService.setCurrentDivision(division);
  }

详细表格的代码是:

divisionService = inject(DivisionService);
  constructor(private fb: UntypedFormBuilder) {

    console.log(this.divisionService.getCurrentDivision());
    this.division = this.divisionService.getCurrentDivision();
  }

我应该能够在控制台中看到对象值,并且当我执行设置时我可以看到它已填充,但当我检索它时它会变成空。

angular angular-services
1个回答
1
投票

问题是,您将自己锁定为当前信号值

   this.division = this.divisionService.getCurrentDivision();

要使信号发挥作用,您必须一遍又一遍地获取它的值(通过

yourSignal()

因此,要么从服务返回

Signal<Devision>
,要么将组件属性更改为
getter
,这样每次访问最终都会访问信号值

ivisionService = inject(DivisionService);
  constructor(private fb: UntypedFormBuilder) {
    console.log(this.divisionService.getCurrentDivision());
  }

  get division(){
//this will do the trick
    this.divisionService.getCurrentDivision();
  }
© www.soinside.com 2019 - 2024. All rights reserved.