如何在不复制数组的情况下创建对现有数组的新引用



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

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引用而不增加复杂性

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

你尝试更改引用呢,实际上它不会更改引用,你只是更改一个包含引用的变量:

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();

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

@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>

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

最新更新