0

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?

Steven
  • 61
  • 1
  • 3
  • 10

1 Answers1

1

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.

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • The user list is always loaded when the list component is opened by the user. when the user clicks on a list item - the underlying user object should be used in the user detail component. the whole user list items should not be cached in the service since it should be stateless and the user list is loaded several times. only the navigation between list component und detail mask should not result in a backend call and should use the object provided "in the list" – Steven Sep 04 '18 at 07:16