1

I am working with angular and firebase. I have 170 products in firebase. when I call the firebase I get the Observable of the products which stored in products$.

Problem: I would like to shuffle all the products among themselves. So that when I refresh the web page, every time the product list will be different. I tried the array method but it doesn't work as products$ is an Observable not array! What I could do? Thanks in Advance!

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>
Faysal Ovi
  • 35
  • 5
  • 5
    `products$` is an observable of an array, so you can pipe in a `map` operator that shuffles the array. – jBuchholz Nov 02 '21 at 15:16
  • @jBuchholz, should I take a new variable and call the products$ after storing all the products? – Faysal Ovi Nov 02 '21 at 18:19
  • As you are mapping the values... `map((sps) => sps.map((sp) => ({ key: sp.key, ...sp.payload.val() })))` after that... shuffle the array just like jBuchholz said :) No need for any other variables. – AT82 Nov 02 '21 at 18:38

2 Answers2

2

For sure there is a better/shorter way to do this, but you can try using a "BehaviourSubject" and pass it your array, sorted as you like (randomly in this case).

You can try something like this:

  1. Add this to your product.component.ts:
// product.component.ts

import { ActivatedRoute } from '@angular/router';
import { Component } from '@angular/core';
import { BehaviorSubject, Observable, of, Subscription } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

import { Product } from './../models/product';
import { Cart } from './../models/cart';
import { CartService } from './../cart.service';
import { ProductsService } from './../products.service';

@Component({
  selector: 'products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
})
export class ProductsComponent {
  products$: Observable<Product[]>;
  randomProductsSource = new BehaviorSubject<Product[] | null>(null);
  randomProducts$ = this.randomProductsSource.asObservable();
  cart$: Observable<Cart>;

  constructor(
    private productsService: ProductsService,
    private cartService: CartService,
    private route: ActivatedRoute
  ) {
    this.getProducts();
    this.getCart();

    this.products$.subscribe( _products => {
      if ( _products && products?.length > 0) { 
         this.randomizeArray(_products);
         this.setRandomProducts(_products);
      }
    })

  }

  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
            )
        )
      );
  }

  private setRandomProducts(data: Product[] | null) {
    this.randomProductsSource.next(data);
  }

  private randomizeArray(arrayProducts) {
     for (let i = arrayProducts.length-1; i > 0; i--) {
        const j = Math.floor( Math.random()*(i+1) );
        [arrayProducts[i], arrayProducts[j]] = [arrayProducts[j], arrayProducts[i]];
     }
  }


}


  1. Then change in your product.component.html, just change products$ by randomProducts$:
<div *ngIf="(randomProducts$ | async)?.length === 0" class="alert alert-info" role="alert">

I got the idea of the randomize method from HERE

  • doesn't work. Get Error here, setRandomProducts(data: Product[] | null) { this.randomProductsSource.next(data); } randomizeArray(arrayProducts) { for (let i = arrayProducts.length-1; i > 0; i--) { const j = Math.floor( Math.random()*(i+1) ); [arrayProducts[i], arrayProducts[j]] = [arrayProducts[j], arrayProducts[i]]; }, doesn't exist on type 'ProductsComponent' – Faysal Ovi Nov 02 '21 at 18:09
  • I'm sorry, I will edit my answer and will merge my code into yours. – Juan Vicente Berzosa Tejero Nov 02 '21 at 18:17
  • Thank you so much! it is absolutely the thing that I wanted!! For approving this answer I need 2 more reputations. Could you please make an uptick in my question so that I could approve the answer? Lots of Thanks again. – Faysal Ovi Nov 02 '21 at 20:04
  • 1
  • Wow! All those codes just to randomize records. Isn't it time to go back to SQL? LOL – Jhourlad Estrella Apr 01 '23 at 06:25
0

Just add an additional step to your mapping, where you actually shuffle the array before returning it. However you want to shuffle it, is a choice, here are several options: How to randomize (shuffle) a JavaScript array? One of the answers there introduces this:

/* Randomize array in-place using Durstenfeld shuffle algorithm */
shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

So just call this function at the point you want to shuffle the array. An appropriate time would be inside your getProducts function after doing the filter:

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);
    }),
    // Shuffle the array before returning it!
    map((products: Product[]) => this.shuffleArray(products))
  );
}
AT82
  • 71,416
  • 24
  • 140
  • 167