服务信号更新时调用组件方法

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

让我以大约一个月前开始学习 Angular 的事实来回答这个问题。

基本上,我有一个搜索栏组件和几个不同的项目容器组件(每个组件都显示不同类型的项目)。为了尝试访问任何组件上的 serchbar 值,我创建了一个 searchbarService,如下所示:

import { Injectable, signal, WritableSignal } from '@angular/core';

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

  searchTextSignal: WritableSignal<string> = signal('');

  setSearch(text: string): void{
    this.searchTextSignal.set(text);
  }
}

搜索栏组件在输入提交时调用 setSearch 方法。到目前为止,一切都很好。现在,当尝试在 itemcontainter 组件上使用 searchTextSignal 时,问题就出现了。我尝试像这样使用它:

import { Component, signal} from '@angular/core';
import { Factura } from 'src/app/interfaces/factura';
import { FacturaService } from 'src/app/services/factura.service'; //gets items from a placeholder array.
import { SearchBarService } from 'src/app/services/search-bar.service';

@Component({
  selector: 'vista-facturas',
  templateUrl: './vista-facturas.component.html',
  styleUrls: ['./vista-facturas.component.css']
})
export class VistaFacturasComponent {

    facturasArray: Factura[] = []; // has all items
    filteredFacturasArray = signal<Factura[]>([]); // has all filtered items, and is the value that I want to get updated when the signal changes.

    constructor(private facturaService: FacturaService, public searchBarService: SearchBarService) { }

    getFacturas(): void { //initializes the arrays.
        this.facturaService.getFacturas().subscribe(facturasReturned => this.facturasArray = facturasReturned);
        this.filteredFacturasArray.set(this.facturasArray);
    }

    filterFacturas(): void{ // this method is likely the problem

        let text = this.searchBarService.searchTextSignal();

        if (!text) 
            this.filteredFacturasArray.set(this.facturasArray);
        
        this.filteredFacturasArray.set(this.facturasArray.filter(factura => factura?.numero.toString().includes(text)));
    }

    ngOnInit(): void {
        this.getFacturas();
    }
}

模板使用 ngFor 像这样:

<div class="item-container">
    <div class="item" *ngFor="let factura of filteredFacturasArray()"> 
         <!-- template for the items -->
    </div>
</div>

所以,一切都归结为如何让 VistaFacturasComponent 在 searchBarService.searchTextSignal() 更新时调用 filterFacturas() 。有什么想法吗?

angular typescript signals angular16
1个回答
0
投票

您可以使用 effects 来挂钩信号变化,effect 是一种每当一个或多个信号值发生变化时就会运行的操作。 您可以在构造函数中使用效果来改变信号。

constructor(
    private facturaService: FacturaService,
    public searchBarService: SearchBarService
  ) {
    effect(() => {
      this.filterFacturas();
    });
  }

这里是一个 stackblitz 链接。如果有帮助请点赞/投票

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