问题
I have a array of thread objects, each thread object with the properties
unit:number
task:number
subtask:number
I want to create a pipe to filter after these threads, so far I have a working pipe like below. I'm not really satisfied with it yet and wanted to ask you guys if there is a more elegant solution?
HTML:
<div class="thread-item" *ngFor="#thread of threadlist | threadPipe:unitPipe:taskPipe:subtaskPipe"></div>
Pipe.ts
export class ThreadPipe implements PipeTransform{
threadlistCopy:Thread[]=[];
transform(array:Thread[], [unit,task,subtask]):any{
//See all Threads
if(unit == 0 && task == 0 && subtask == 0){
return array
}
//See selected Units only
if(unit != 0 && task == 0 && subtask == 0){
this.threadlistCopy=[];
for (var i = 0; i<array.length;i++){
if(array[i].unit == unit){
this.threadlistCopy.push(array[i])
}
}
return this.threadlistCopy
}
//See selected Units and Tasks
if (unit != 0 && task != 0 && subtask == 0){
this.threadlistCopy=[];
for (var i = 0; i<array.length;i++){
if(array[i].unit == unit && array[i].task == task){
this.threadlistCopy.push(array[i])
}
}
return this.threadlistCopy
}
// See selected units, tasks, subtask
if (unit != 0 && task != 0 && subtask != 0){
this.threadlistCopy=[];
for (var i = 0; i<array.length;i++){
if(array[i].unit == unit && array[i].task == task && array[i].subtask == subtask){
this.threadlistCopy.push(array[i])
}
}
return this.threadlistCopy
}
}
}
回答1:
You are implementing your pipe the right way, but you are basically re-inventing the Array.prototype.filter mechanism in your code. A simpler way will be:
export class ThreadPipe implements PipeTransform{
transform(array:Thread[], [unit,task,subtask]):any{
//See all Threads
if(unit == 0 && task == 0 && subtask == 0){
return array
}
//See selected Units only
if(unit != 0 && task == 0 && subtask == 0){
return array.filter(thread => {
return thread.unit === unit;
});
}
//See selected Units and Tasks
if (unit != 0 && task != 0 && subtask == 0){
return array.filter(thread => {
return thread.unit === unit && thread.task === task;
});
}
// See selected units, tasks, subtask
if (unit != 0 && task != 0 && subtask != 0){
return array.filter(thread => {
return thread.unit === unit && thread.task === task && thread.subtask === subtask;
});
}
}
}
来源:https://stackoverflow.com/questions/36423903/angular2-pipe-for-multiple-arguments