@@ -6,6 +6,7 @@ import { catchError, map, tap } from 'rxjs/operators';
66import { throwError } from 'rxjs' ;
77
88import { Place } from '../models/place.model' ;
9+ import { ErrorService } from './error.service' ;
910
1011@Injectable ( {
1112 providedIn : 'root' ,
@@ -15,22 +16,61 @@ export class PlacesService {
1516 loadedUserPlaces = this . userPlaces . asReadonly ( ) ;
1617
1718 private http = inject ( HttpClient ) ;
19+ private errorServ = inject ( ErrorService ) ;
1820
1921 loadAvailablePlaces ( ) {
2022 return this . fetchPlaces ( '/api/v2/places' , 'Error loading available places!' ) ;
2123 }
2224
2325 loadUserPlaces ( ) {
24- return this . fetchPlaces ( '/api/v2/user-places' , 'Error loading user places!' ) ;
26+ return this . fetchPlaces ( '/api/v2/user-places' , 'Error loading user places!' ) . pipe (
27+ tap ( {
28+ next : resp => {
29+ if ( resp ) {
30+ this . userPlaces . set ( resp . places ) ;
31+ }
32+ } ,
33+ } ) ,
34+ ) ;
2535 }
2636
27- addPlaceToUserPlaces ( placeId : string ) {
28- return this . http . put ( '/api/v2/user-places' , {
29- placeId,
30- } ) ;
37+ addPlaceToUserPlaces ( place : Place ) {
38+ const prevPlaces = this . userPlaces ( ) ;
39+
40+ if ( ! prevPlaces . some ( p => p . id === place . id ) ) {
41+ // optimistic update
42+ this . userPlaces . set ( [ ...prevPlaces , place ] ) ;
43+ }
44+
45+ return this . http
46+ . put ( '/api/v2/user-places' , {
47+ placeId : place . id ,
48+ } )
49+ . pipe (
50+ catchError ( err => {
51+ this . userPlaces . set ( prevPlaces ) ;
52+ this . errorServ . showError ( 'Unable to store the selected place!' ) ;
53+ return throwError ( ( ) => new Error ( 'Unable to store the selected place!' ) ) ;
54+ } ) ,
55+ ) ;
3156 }
3257
33- removeUserPlace ( place : Place ) { }
58+ removeUserPlace ( place : Place ) {
59+ const prevPlaces = this . userPlaces ( ) ;
60+
61+ if ( prevPlaces . some ( p => p . id === place . id ) ) {
62+ // optimistic update
63+ this . userPlaces . set ( prevPlaces . filter ( pl => pl . id !== place . id ) ) ;
64+ }
65+
66+ return this . http . delete ( '/api/v2/user-places/' + place . id ) . pipe (
67+ catchError ( err => {
68+ this . userPlaces . set ( prevPlaces ) ;
69+ this . errorServ . showError ( 'Unable to remove the selected place!' ) ;
70+ return throwError ( ( ) => new Error ( 'Unable to remove the selected place!' ) ) ;
71+ } ) ,
72+ ) ;
73+ }
3474
3575 private fetchPlaces ( url : string , errMsg : string ) {
3676 return this . http
0 commit comments