我有一个使用 rest api 的角度服务。
@Injectable({
providedIn: 'root'
})
export class ProductService {
private url: string = "/app/products";
constructor(private http: HttpClient) {
}
get(caregoryId: string) {
return this.http.get<Product[]>(`${this.url}`)
.pipe(map(products => products.filter(p => p.caregoryId == caregoryId)))
}
add(p: Product) {
return this.http.post<Product>(this.url, p);
}
}
我的组件是:
export class ProductComponent implements OnInit{
items: Observable<Array<Product>>;
ngOnInit() {
this.route.params.subscribe(
(params: any) => {
this.items = this.productService.get(params.id);
})
}
addWidget() {
let item: any = { name: "p-1", color: "red" } }
this.productService.add(item))
/// how to add created item in my items array ?
}
}
我可以获取产品列表并使用 html 中的异步管道列出它们。但是我无法在我的可观察数组中添加创建的项目。我该怎么做?
items$
您可以使用rxjs#Subject
,rxjs#merge
和rxjs#scan
控制数据流,而不是每次在列表中执行操作(添加、删除、更新等)时都重新分配。rxjs#switchMap
并执行以下操作:this.activatedRoute.paramMap.pipe( map(paramMap => paramMap.get('id')), switchMap(id => this.productsService.getItems(id)) )
caRegory
:)有了这些变化,我们有了:
@Component({
// ...
})
export class AppComponent {
readonly items$: Observable<readonly Product[]>;
private readonly itemInsertedSource$ = new Subject<Product>();
private readonly itemInserted$ = this.itemInsertedSource$.asObservable();
constructor(
private readonly activatedRoute: ActivatedRoute,
private readonly productsService: ProductsService
) {
this.items$ = merge(
this.activatedRoute.paramMap.pipe(
map(paramMap => paramMap.get('id')),
switchMap(id => this.productsService.getItems(id))
),
this.itemInserted$
).pipe(scan((acc, value) => [...acc, value]));
}
addWidget(): void {
const item: Product = { color: 'purple', name: 'p-3' };
this.productsService.add(item).subscribe(itemInserted => this.itemInsertedSource$.next(itemInserted));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句