【问题标题】:How to create new reference to existing array without copying the array如何在不复制数组的情况下创建对现有数组的新引用
【发布时间】:2019-11-30 12:58:33
【问题描述】:

是否可以在不通过数组的情况下创建对数组的新引用? 我的问题是我有一个纯角管,它不能检测到推/弹出变化。我想避免这样的解决方案:

this.array = this.array.filter(e=>true)

这增加了复杂性只是为了更新参考。 我已经尝试了第一件事,但它不起作用(管道没有检测到任何变化)而且我对 js/ts 的熟悉程度不足以知道它为什么不起作用。

const newRef = this.array;
this.array = null;
this.array = newRef

我有获取对象数组和过滤器数组并返回过滤对象数组的管道。

@Pipe({
  name: 'eventFilter'
})
export class EventFilterPipe implements PipeTransform {

  transform(events: EventDtos[], filters:Filter[]): any {
     //return filtered events
  }

管道使用情况:

<div  class="event" *ngFor="let event of events  | eventFilter:filters">
   html stuff
</div>

filters 推送/弹出过滤器后,管道的转换未被调用,因此我使用此代码强制transform 调用:

this.filters = this.filters.filter(e=>true)

但此时我不知道哪个更快,这种方法还是不纯的管道。所以理想情况下我想离开纯管道并更新filters参考而不增加复杂性

【问题讨论】:

  • 您的样本最后应该创建对数组的引用。您能否详细说明您使用的是什么管道以及它为什么/如何不起作用?
  • @JeffryHouser 我添加了更多细节

标签: javascript angular typescript reference pipe


【解决方案1】:

我不建议你使用不纯管道,它会在每次变更检测时执行并过滤事件,每秒可能有数百次变更检测。

你尝试改变引用呢,实际上它并没有改变引用,你只是改变了一个包含引用的变量:

const newRef = this.array; // newRef references the array
this.array = null;
this.array = newRef // this.array references the same array, nothing is changed

因此,正如您所做的那样,复制数组是更好的解决方案,但有更简单的方法:

this.array = [...this.array];
// or
this.array = this.array.slice();

另一种解决方案是使用SubjectAsyncPipe。在这种情况下,不需要复制数组。如果数组很大,或者过滤器经常更换,这可能是首选方式:

@Component({...})
class MyComponent {
    readonly filters$ = new BehaviourValue<Filter>([]);

    ...
    addFilter(filter: Filter): void {
        this.filters$.value.push(filter);
        this.filters$.next(this.filters$.value);
    }
}
<div  class="event" *ngFor="let event of events | eventFilter:(filters$ | async)">
   html stuff
</div>

【讨论】:

    【解决方案2】:

    您可能在 Angular 中寻找不纯的管道吗?这样,您的管道会针对每个输入更改自动更新。更多信息可以参考官方指南https://angular.io/guide/pipes#pure-and-impure-pipes

    【讨论】:

    • 理想情况下我想留下纯管道,因为它更快
    猜你喜欢
    • 2022-01-22
    • 2016-02-24
    • 2010-11-25
    • 2023-02-11
    • 2012-12-24
    • 2020-08-21
    • 2020-11-26
    • 2015-12-30
    相关资源
    最近更新 更多