Update Inventory roles from custom Angular app

I am developing a custom application in Angular, based on @c8y/websdk’s application, to then incorporate it into my cumulocity platform, on said angular application I have made a form to create a new user with certain specific parameters, but at the same time I need specify certain inventory role privileges to a specific group. So my problem is that I cannot find the appropriate documentation to update the groups and inventory role privileges to be associated. Is there a websdk service of type inventoryRoles.update()?

I have tried to perform the update through fetch()… but it asks me for credentials to perform this action.

How could I perform this action without passing on credentials or taking them from the logged in user?

Hi @dacsystemsw,

you might be looking for these services: InventoryRoleService and UserInventoryRoleService.

If you want to perform requests using fetch against your tenant with the corresponding credentials, you can use the fetch method provided by the FetchClient.

Regards,
Tristan

Hi @Tristan_Bastian

using, UserInventoryRoleService, gives me these Error:

Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[UserInventoryRoleService → UserInventoryRoleService]:,

Reminding you that I’m building an angular application using @c8y/websdk,
on the other hand using fetch, when making the POST call, it gives me a 401(Unauthorized)

Hi @dacsystemsw,

You can use the inventoryAssignment method of the UserService to get an instance of the UserInventoryRoleService for that specific user.

And as said before if you want to access some endpoint that might not be covered by the @c8y/client package, you can dependency inject the FetchClient and use it’s fetch method. Using the fetch method provided by the FetchClient will take care of adding the required headers for authorization. If you are using the global fetch function instead, these headers will be missing.

In case you are having further issues, please provide code snippets and the version of the c8y packages you are using.

Regards,
Tristan

This is my snippet @Tristan_Bastian , can you please help me to check what is wrong?

import { Component } from '@angular/core';
import {
  UserService, IResultList, IUser, IResult, ApplicationService,
  IApplication, IUserInventoryRole
} from '@c8y/client';
import { AppStateService, User } from '@c8y/ngx-components';

@Component({
  selector: 'app-add-user',
  templateUrl: './add-user.component.html',
  styleUrls: ['./add-user.component.css']
})

export class AddUserComponent {
  selectedOption: string = '';
  newUserName: string = '';

  setAppDashboard: any;
  setTenant: string = '';
  setDomain?: string = '';

  constructor(private userService: UserService, .....) {
  }


  addNewUser(): void {
    const newUser: User = {
      userName: 'demo',
      password: 'demo',
      displayName: 'Demo User test',
      phone: '',
      email: 'demo@mydomain.com',
      sendPasswordResetEmail: false,
      groups: {
        references: [
          {
            group: {
              name: 'GroupName',
              id: 16,
            }
          }
        ],
      },
    };

    //Create User work nice 
    this.userService.create(newUser).then((userResult: IResult<IUser>) => {
      const partialUpdateObject: Partial<IUser> = {
        id: userResult.data.id,
        applications: [this.setAppDashboard.data[0]]
      };

      //Update works nice
      this.userService.update(partialUpdateObject);


      ///Assign Inventory Roles to a single group XXX for this newUser: dont work properly
      const myGroupId = '444444480';
      const inventoryRoleId = 1;

      const obj = { managedObject: myGroupId, roles: [{ id: inventoryRoleId }] };
      const options = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(obj)
      };

      const url = `/user/${this.setTenant}/users/${userResult.data.userName}/roles/inventory`;
      try {
        const response = await fetch(url, options);

        if (!response.ok) {
          throw new Error(`Error ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        console.log('Response data:', data);
      } catch (error) {
        console.error('Error:', error);
      }


    }).catch(error => {
      console.error('Error occurred: ', error);
    });
  }
}

You would need to dependency inject the FetchClient:

import { FetchClient } from '@c8y/client';
...
constructor(private userService: UserService, private fetchClient: FetchClient, .....) {
  }

And then you could call fetch on the fetchClient:

const response = await this.fetchClient.fetch(url, options);

Regards,
Tristan

@Tristan_Bastian , i’ve already did this before, and show me a popup to input the credentials
Screenshot from 2024-06-20 14-10-36

Are you developing an app or a plugin?
Are you calling CoreModule.forRoot() in more than one place? In which locations are you calling CoreModule.forRoot()?

@Tristan_Bastian, i’m developing an application from @c8y/websdk, and CoreModule.forRoot(), i use it only in app.module.ts

Feel free to upload a minimal sample that reproduces your issue to some external service.
You can send the link to that sample directly via a personal message to me.