Tips for effectively handling the data received from a webservice when logging into a system

My web service provides me with permissions from my user. The permissions are stored as an array in JSON format. I need to find a way to access and display this data in another function.

{"StatusCode":0,"StatusMessage":"Authenticated Successfully",
"Token":"fgfhgjhgkfgddfgggffhhfazcfdddd",
"StatusDescription":{
"permissions":["usersgetall","usersdelete","usersupdate","clientgetall",
"clientupdate","clientdelete"....]}
"role":"root"
}

The login function that I have is structured like this: How can I create a new function that will list all the permissions for a specific user?

public loginByUsernameAndPassword(username: string, password: string): Observable<boolean> {

    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('username', username);
    urlSearchParams.append('password', password);
    urlSearchParams.append('user_uniqueIdid', '0');
    urlSearchParams.append('session_id', '0');
    let body = urlSearchParams.toString();

    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return this.http.post(Api.getUrl(Api.URLS.Login), body, {
      headers: headers
    })
      .map((response: Response) => {
        let res = response.json(); 
         console.log(rs)// show Permissions[]
          if (res.StatusCode === 0 && res.Token) {
          this.currentUser = {
            username: username,
            token: res.Token
          }
          localStorage.setItem(AuthService.CURRENT_USER, JSON.stringify(this.currentUser));
          return true;
           } else {
          return false;
        }
      });
  }

Answer №1

responseJSON() converts res:Response into an object, allowing easy access to properties.

fetchPermissions(jsonObj:any){
    return jsonObj.StatusDetails.permissions
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Most Effective Approach for Handling Multiple Fetch Requests Concurrently using Async-Await in TypeScript?

I am currently exploring the idea of making multiple API calls simultaneously by utilizing multiple fetch requests within an await Promise.all block, as shown below: const responseData = await Promise.all([ fetch( DASHBOARDS_API + "getGoal ...

Issue with displaying data in *ngFor after service call in Angular 9 - Data is retrieved and stored in the list,

My code example is working with the API end point and I received a response. However, I am facing an issue with displaying the data using *ngFor in my Angular component. In the ngOnInit method of category-list.component.ts, I'm calling a service to fe ...

Obtain an instance tuple from tuple classes using TypeScript 3.0 generic rest tuples type

When it comes to retrieving the correct instance type from a class type, the process typically involves using the following code: type Constructor<T = {}> = new (...args: any[]) => T class Foo {} function getInstanceFromClass<T>(Klass: Co ...

Showing Arrays in Angular on HTML Page

I have created an array that stores multiple arrays with 3 indexes each. An example of the structure looks like this: (3) [Array(3), Array(3), Array(3)] 0: (3) [199.4, 10.5, 19] 1: (3) [47.2, 2.1, 23] 2: (3) [133.6, 5.3, 25] In my HTML, I want to display ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

Why is NestJs having trouble resolving dependencies?

Recently delving into NestJs, I followed the configuration instructions outlined in https://docs.nestjs.com/techniques/database, but I am struggling to identify the issue within my code. Error: Nest cannot resolve dependencies of the AdminRepository ...

Node.js: Handling Undefined Request Parameters

My get route is set up to receive two parameters "limit" and "page". router.get('/:limit/:page', userController.list); class UserController{ public list(req:Request, res:Response): void{ const limit:number = +req.params.limit || 25; ...

What is the source of Docker's node version information?

Within the Dockerfile, I specified the version node:14.17.6-alpine3.13. However, in the deployment log, it shows a different version, node:16.13.2-alpine. Can anyone shed light on why this discrepancy exists and how to rectify it? docker-compose deploy lo ...

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

Encountering an error in TypeScript and ng2 rc.1: Error message (20, 15) TS2304 indicates that the name 'module' cannot be found

Having trouble with TypeScript and ng2 rc.1 - getting Error:(20, 15) TS2304: Cannot find name 'module'. I encountered this issue when trying to use a directive of the module in my code: @Component({ selector: 'Notes1', moduleI ...

Application built with Electron and Typescript encounters module-related crash

While working on developing a client using Electron with Typescript, I encountered the following error: The configuration in tsconfig.json looks like this: { "compilerOptions": { "target": "es5", "lib": [ ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

Sending every piece of information to the URL may not be the most efficient approach, in my opinion

Lately, I have incorporated NodeJS into my Angular project and here is how I am currently implementing it: Node : app.get('/register/:username/:password', function(req, res){ db.collection('users').insertOne({ username: req ...

Troubleshooting tip: The request body is missing and needs to be added to resolve the issue

I am encountering an issue while trying to update a boolean column in my database for approving customer accounts using an angular front-end button. Whenever I send the request, my controller throws an error stating Resolved [org.springframework.http.conve ...

Having issues with Angular http.post not sending data when using subscribe

I'm currently facing an issue with sending data to my API using post.subscribe. Despite the fact that no errors are being thrown, the data is not being sent successfully. It's important to note that the API itself is functioning perfectly. Belo ...

When setting up Webpack with TypeScript, an error is encountered related to imports

Recently, I attempted to convert my Webpack configuration from JavaScript to TypeScript but encountered numerous difficulties in the process. To kick things off, I created a basic webpack configuration file with some parts missing. Here is how my webpack.c ...

"Exploring the process of accessing the request headers section within the network tab of your browser

How can I extract the access date from the request headers section in the network tab of my browser when receiving a response from the API? Can someone help me with this problem? ...

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Applying styles to every tr element in Angular 2 components

I'm trying to use background-color with [ngClass] on a table row. The styles are being applied, but they're affecting all rows' backgrounds. I want the background color to only change for the specific row that is clicked. Here is my code: ...