I'm searching by the ids in the array. But if the array is empty, I want all the data to come. How can I do it?
selectedUrunGrubus: number[] = [];
urun: Urun[];
getUruns() {
this.generic?.Get_All("Uruns/Generic_Method").pipe(map(hizmets => hizmets.filter(hizmets => (this.selectedUrunGrubus.includes(hizmets.urunGrubuID) && this.selectedUrunGrubus.length>0)))).subscribe({
next: (data) => { this.urun = data; console.log(this.urun) },
error: (err) => { console.log(err) },
complete: () => {
}
});
}
this.urun = [id=1] [id=2] [id=3] [id=4];
if(selectedUrunGrubus == [1,2])
{
this.urun = [id=1] [id=2]
}
if(selectedUrunGrubus == empty)
{
this.urun = [id=1] [id=2] [id=3] [id=4]
}
CodePudding user response:
The reason why your array is empty is because of the this.selectedUrunGrubus.length>0 conditional inside your filter. The length of selectedUrunGrubus starts at 0, so the expression will always be false.
Here's another strategy you can use. Assign the filtered array to a variable, then return a ternary expression for either case.
selectedUrunGrubus: number[] = [];
urun: Urun[];
getUruns() {
this.generic?.Get_All("Uruns/Generic_Method")
.pipe(
map(hizmets =>{
const matches = hizmets.filter(hizmet => this.selectedUrunGrubus.includes(hizmet.urunGrubuID));
return !!matches.length ? matches : hizmets;
}),
tap(urun=> this.urun = urun)
).subscribe();
}
Note:
- I used double bangs
!!to convert the length into a boolean (since0is falsy) - Use
tap()to handle side effects like property assignments. - The rest of your logic inside
subscribe()is default behavior, so you can just use a basicsubscribe()at the end.
