One of the common issues I see developers struggling with is to get the logged in user details in SAPUI5 application.
Suppose there is a requirement under which you want show logged in user’s details in your SAPUI5 application like username or user ID or user email etc. Then I have seen many developers not finding any working solution on client side (FE) for the problem and doing and a backend call to fetch the user details.
SAP HANA Cloud Platform provides a service called User API which can provide the user information on SAP WEB IDE without doing an explicit backend OData call. For more information about the service, you can refer SAP HANA Cloud Platform documentation.
This API provide the logged in user details at the application level from SAP HANA Cloud Platform. By using this API you can see following details:-
name (User ID)
Display Name (Full name with User ID)
Now let us see the step by step guide to include and use this user API in your Application.
First add the below given code snippet in your application's neo-app.json
This will add a route for SAP HANA Cloud Platform user API in the application.
The text code is also included to make it easier to use…
Create a JSON model to consume the service.In this example I am creating a global model so that the user information is available throughout the application.
Above example will create a global model over the User API service to consume the current logged in user details.
var oModel = new JSONModel("/services/userapi/currentUser");
Now we will set this model in Component.jsNow the model is set, and we can use it in our views and controllers as per the requirement.
NOTE: - You can also create the model directly in Manifest.json file or if only needed in single view, then you can also create a local model. It completely depends on your requirement
The model data will contain following information as shown in image below: -
As you can see all the basic user information is available to use as per requirement.
This way you can easily fetch the user details in your application without any extra backend call. It is way faster and and more efficient way of fetching the user details of whoever is currently using the application. The data will only contain a single object with 5 key-value pairs as shown above in the last step or mentioned at the beginning of the post.
NOTE:- Only the Current User details can be fetched using this API. It will not provide details about all user who has accessed the application.