Home > Net >  Adding additional entry to observable returned data to be used at the api call level
Adding additional entry to observable returned data to be used at the api call level

Time:02-17

I have a number of food item list services like:

getFruits(): Observable<Fruit[]> {
    return this.apiService.get<Fruit[]>(this.fruitUrl);
}

I have many forms where they call this for the entire list of items then user saves the form. I have a feature where user can delete items from the list (e.g. remove Apple from fruits list) but when user loads a saved form, i want the original fruit item to be in the list if it was removed (e.g. if Apple was removed after I saved a form with Apple as part of dropdown. When I load the list the Apple needs to be there). What I want is to add the missing selected item to the list IF it wasn't in there.

I did look around and it seems a lot of solutions revolves around after getting the data then add new entry to it. With so many forms I have I don't think thats ideal. Is there a way to add the entry to the "getFruits()" by passing in the Fruit name and if it doesnt exist then I add the entry then return the result?

I tried something like

    let fruits = this.apiService.get<Fruit[]>(this.fruitUrl);
 let newFruit = new Fruit();
 newFruit.name = "Apple";
 newFruit.id = 999;
 let fruits1;
 fruits.pipe(map(fruits1=> [...fruits1, newFruit]));

return fruits;

but the list is still what was returned from the call. Am I doing something wrong?

CodePudding user response:

You don't want to use tap to modify an array. Instead use map to create a new one.

fruits.pipe(map(fruits1=> [...fruits1, newFruit]));

In general you'll be happier not modifying things and just creating new instances. The lack of side effects is a good thing.

CodePudding user response:

Is there a way to add the entry to the "getFruits()" by passing in the Fruit name and if it doesnt exist then I add the entry then return the result

Use map with a ternary condition:

getFruits(newFruit: Fruit): Observable<Fruit[]> {
    return this.apiService.get<Fruit[]>(this.fruitUrl).pipe(
      map(fruits => fruits.find(f => f.name === newFruit.name)
        ? fruits 
        : [...fruits, newFruit]
      )
    );
}

  • Related