angulardata-sharing

Share complex objects between two independent angular (>=5) components


I have a components which displays a list of users (UserListComponent) The model bound model is a list of user objects received by a userService using httpclient.

When user clicks on item (user) in the list a component (UserDetailsComponent) should open where to edit the user.

Therefore I want to pass the user objects to the detail component.

Normally, I would just pass an id of the route, use a guard and load the whole user object by that id using the userService.

In my special case we dont want a backend call and pass the object as it is without a backend call.

What is the best way to do it? Another shared service?


Solution

  • You can use the same UserService you are already using. Sounds like you just want it to load once during an App instance (or perhaps when there is a force refresh button?). Anyways, you can do something like this:

    @Injectable()
    export class UserService {
    
      readonly users: Observable<User[]> = this.http.get('https://some.url/users).pipe(
        shareReplay()
      );
    
      readonly user: Observable<User | undefined> = this.route.params.pipe(
        map(({ user }) => user),
        mergeMap((userId) =>
          userId ? this.users.pipe(
            map((users) => users.find((user) => user.id === userId))
          ) : of(void 0)
        )
      )
    
      constructor(readonly http: HttpClient, readonly route: ActivatedRoute) {}
    }
    

    Be aware though, this is untested code, but you probably get the idea. Just keep everything as observables and use the router to update the observable. You should use the async pipe in the templates to display the data.