【发布时间】:2021-12-17 02:47:04
【问题描述】:
我正在使用 Angular 和 Firebase。我在 Firebase 中有 170 种产品。当我调用 firebase 时,我得到了存储在 products$ 中的产品的 Observable。
问题:我想将所有产品相互洗牌。这样当我刷新网页时,每次的产品列表都会不一样。我尝试了数组方法,但它不起作用,因为 products$ 是 Observable 而不是数组! 我能做什么?提前致谢!
product.component.ts
import { Product } from './../models/product';
import { Cart } from './../models/cart';
import { CartService } from './../cart.service';
import { ActivatedRoute } from '@angular/router';
import { ProductsService } from './../products.service';
import { map, switchMap } from 'rxjs/operators';
import { Observable, of, Subscription } from 'rxjs';
import { Component } from '@angular/core';
@Component({
selector: 'products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css'],
})
export class ProductsComponent {
products$: Observable<Product[]>;
cart$: Observable<Cart>;
constructor(
private productsService: ProductsService,
private cartService: CartService,
private route: ActivatedRoute
) {
this.getProducts();
this.getCart();
}
private getProducts(): void {
this.products$ = this.route.queryParamMap.pipe(
switchMap((params) => {
if (!params) return of(null);
let category = params.get('category');
return this.applyFilter(category);
})
);
}
private applyFilter(category: string): Observable<Product[]> {
if (!category)
return this.productsService
.getAll()
.snapshotChanges()
.pipe(
map((sps) => sps.map((sp) => ({ key: sp.key, ...sp.payload.val() })))
);
return this.productsService
.getByCategory(category)
.snapshotChanges()
.pipe(
map((sps) => sps.map((sp) => ({ key: sp.key, ...sp.payload.val() })))
);
}
private async getCart() {
this.cart$ = (await this.cartService.getCart())
.snapshotChanges()
.pipe(
map(
(sc) =>
new Cart(
sc.key,
sc.payload.val().cartLines,
sc.payload.val().createdOn
)
)
);
}
}
product.component.html
<div class="row">
<div class="col-3">
<products-filter></products-filter>
</div>
<div class="col-9">
<div *ngIf="cart$ | async as cart" class="row">
<ng-container *ngFor="let product of products$ | async; let i = index">
<div class="col">
<product-card [product]="product" [cart]="cart"></product-card>
<div *ngIf="(i + 1) % 2 === 0" class="row row-cols-2"></div>
</div>
</ng-container>
</div>
<div *ngIf="(products$ | async)?.length === 0" class="alert alert-info" role="alert">
<h1>Keine Produkte gefunden!</h1>
</div>
</div>
</div>
【问题讨论】:
-
products$是一个数组的可观察对象,因此您可以通过管道输入一个map运算符来打乱数组。 -
@jBuchholz,我应该在存储所有产品后取一个新变量并调用 products$ 吗?
-
当您映射值时...
map((sps) => sps.map((sp) => ({ key: sp.key, ...sp.payload.val() })))之后...像 jBuchholz 所说的那样对数组进行洗牌 :) 不需要任何其他变量。
标签: angular angular-observable