in my application I have the task to filter an observable. I have an array of products coming from my server. When the user clicks on a button, 7 random numbers are generated and these are matched with the product array and 7 products are filtered out.
Code from my ProductListComponent Class:
numbers: number[] = [];
filteredproducts: IProduct[] = [];
constructor(private productservice: ProductService) {
}
ngOnInit(): void {
}
getRandomProducts(): void {
let size: number;
this.filteredproducts = [];
this.productservice.getallproducts()
.subscribe(
(products: IProduct[]) => {
size = products.length;
this.getrandomnumbers(size);
console.log(this.numbers);
products.map(
product => {
for (let i = 0; i < this.numbers.length; i++) {
if (Product.Id == this.numbers[i]) {
this.filteredproducts.push(product);
console.log("product added");
}
}
}
)
//this.filteredproducts = products
}
);
}
getrandomnumbers(size: number): void {
for (let i = 0; i < 7; i++) {
this.numbers[i] = Math.floor(Math.random() * size + 1)
}
}
Code from my ProductService Class :
export class ProductService {
private URL = 'http://localhost:3000/products';
constructor(private http: HttpClient) { }
getallproducts(): Observable<IProduct[]> {
return this.http.get<IProduct[]>(this.URL)
}
Everything works fine and the array is filtered. But could I do something to improve it? The code for the function getRandomProducts seems a bit long to me. After that I want the user to be able to go to another page, but to save the products in the list when he comes back to the list page. This does not quite work yet. How would you solve this? I do not want to work with the local cache of the browser. Thanks for your answers.