Shr*_*ree 7 rxjs angular-pipe angular
我正在尝试在异步管道上创建自定义管道,我尝试了很多解决方案,但仍然无法正常工作。这是代码片段。
product.sort.ts - 自定义管道
import { PipeTransform, Pipe } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Pipe({
name: 'sortByName'
})
export class ProductPipe implements PipeTransform{
/*transform(values: Array<any>, term:string){
return values.filter(obj => obj.pname.startsWith(term))
}*/
//CODE NOT WORKING >>>>>
transform($value: Observable<Array<any>>, term:string){
if($value){
$value.subscribe(
(obj) => {
return obj.filter(obj => obj.pname.startsWith(term))
}
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
products.component.ts - 主要组件
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { AppService } from '../app.service/app.service';
import { ProductPipe } from '../products.sort/products.sort';
@Component({
selector: 'products-pg',
template: `
Products List:
<ul>
<li *ngFor = 'let product of $productList | async | sortByName:"A"'>{{product.pname}}</li>
</ul>
`
})
export class ProductsComponent implements OnInit{
private $productList:Observable<Array<any>>;
constructor(private _service: AppService, private _store: Store<Array<any>>){}
ngOnInit(){
this._service.setProductList();
this.$productList = this._store.select('products');
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我使用 store 进行状态管理,我尝试按名称排序,因此将“A”作为第一个字母传递。由于$productList是可观察的,如何编写处理这种异步行为的管道,请帮我解决这个问题。
我也遇到了同样的问题,我修复它的方式是这样的:
<li class="list-group-item" *ngFor='let alert of _alerts$ | ipwrAlertFilter:seeAll | async'>
Run Code Online (Sandbox Code Playgroud)
看看我是如何在异步管道之前使用自定义过滤器的,这样我的自定义管道就会得到一个可观察的,然后在我的管道中我有这个:
return value.map(data => data.filter(x => x.originalHasBeenSeen === false));
Run Code Online (Sandbox Code Playgroud)
这样我的自定义管道仍然返回一些我仍然可以应用异步管道的东西。因此,对于流中的每个新项目,我仍然会在我的自定义管道上获得成功,并且我的视图也会更新。希望这可以帮助。
最好的方法是仍然坚持你的异步,并在异步调用你的自定义管道之后,就像问题中的管道一样,只是你的管道代码现在将更改为不作用于自记录以来要加载的数组仍在加载,因此我们告诉自定义管道不要再执行任何操作或返回空数组。例如
transform(items: any[], field: string, format?: string) {
if (items == null) //since the async is still working
return [];
//do our normal pipe logic or function
return items.sort((a: any, b: any) => {
let value1 = a[field];
let value2 = b[field];
if (value1 > value2) {
return 1;
} else if (value1 < value2) {
return -1;
} else {
return 0;
}
});
Run Code Online (Sandbox Code Playgroud)
那么你的模板仍然保留
*ngFor = 'let product of $productList | async | sortByName:"A"'
Run Code Online (Sandbox Code Playgroud)