CTtXH
CTtXH

Reputation: 19

How to get the current logged in userID in ABP - Angular?

Version: ABP CLI 8.0.1.

I have an option on the website to select an account on the system, I retrieve the account names via the /api/identity/users endpoint like this:

getListWithoutSorting = (input: PagedAndSortedResultRequestDto, config?: Partial<Rest.Config>) =>
    this.restService.request<any, CurrentUserDto[]>({
      method: 'GET',
      url: '/api/identity/users',
      params: { skipCount: input.skipCount, maxResultCount: input.maxResultCount },
    },
      { apiName: this.apiName, ...config });

And I call it in ngOnInit, so the problem is that all other accounts that are not Admin will get a 401 unauthorized error because of the API call, so I wrote a service to check the role of the account

getCurrentUserRole = (userId: string, config?: Partial<Rest.Config>) =>
    this.restService.request<any, { items: any[] }>({
      method: 'GET',
      url: `/api/identity/users/${userId}/roles`,
    },
      { apiName: this.apiName, ...config }).pipe(
        map(response => response.items.map(role => role.name))
      );

Now I need to pass in a userId to check the role, but I haven't figured out how to get the userId for the current logged in user, here is my code:

  ngOnInit() {
    //Get the user role of the current logged in account
    this.userService.getCurrentUserRole("USER_ID").subscribe((roles) => {
      this.isAdmin = roles.includes('admin');
    });

    //Send a request to get the list of users 
    //TODO: If isAdmin is true, get all users, else don't call the service
    const query = { skipCount: 0, maxResultCount: 10 }
    this.userService.getListWithoutSorting(query).subscribe((response) => {
      this.users = response;
    });

    const itemStreamCreator = (query) =>
      this.itemService.getList(query);
    this.list.hookToQuery(itemStreamCreator).subscribe((response) => {
      this.item = response;
    });
  }

Upvotes: 0

Views: 342

Answers (0)

Related Questions