繁体   English   中英

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

[英]How to create new reference to existing array without copying the array

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

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参考

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

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

您尝试更改引用怎么样,实际上它并没有更改引用,您只是更改了一个包含引用的变量:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM