user7117607 user7117607 - 1 month ago 8
Javascript Question

how to handle getallusers vs getuser in userscomponent?

I have a UserComponent and I want it to display a user based on a userId querystring param like this: localhost:3000/users?userId=1

Otherwise, if the url does not have a userId qs param I simply want to display all users: localhost:3000/users

In my code below the first part of the code is still getting run even though there is no qs param:

ngOnInit(): void {

// subscribe to router event
this.subscription = this.activatedRoute.queryParams.subscribe(
(param: any) => {
let userId = param['userId'];
//console.log(userId);
this.getUser(userId);
});

this.getUsers();
}


The first part of the code ends up calling the rest svc for getUser with an undefined userId: http://localhost:4000/users/undefined

How do I need to restructure this code in order to accomodate this scenario?

Answer

I believe, that you need to check if there 'userId' in your subscription callback section

this.subscription = this.activatedRoute.queryParams.subscribe(
      (param: any) => {
        let userId = param['userId'];
        //console.log(userId);

        userId ? this.getUser(userId) : this.getUsers(); 
      });