What is the best method for determining if a certain value is present in an array contained within an object?

Can someone assist me in figuring out the best way to check for admin role using a component in Angular?

Below is the code snippet from the component:

checkIfIsAdmin(): any {
  let user_string = localStorage.getItem("currentUser");

  if (!isNullOrUndefined([user_string])) {
    console.log(user_string);
    return true;
  } else {
    return null;
  }
}

I am trying to verify the ROLE_ADMIN that I receive in the following format:

{
    "longId": 4,
    "name": "bbb",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45272727052228242c296b2628">[email protected]</a>",
    "userName": "bbb",
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNTU5NDk0NTczLCJleHAiOjE1NTk0OTQ4NzN9.XmSHywZv09b4BR9-NxyCTVPF33pLsk3QtTEXQMQF4YHW7i27Ghj2Uh3WZAegpG4rdSImKcm1wMgJsPLpHcTyew",
    "roles": [
        "ROLE_USER",
        "ROLE_ADMIN"
    ]
}

I am unsure about how to iterate through roles within the if condition, can you please guide me on this?

Answer №1

Based on the code provided, it seems that -

user_string = {"longId":4,"name":"bbb","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d2f2f2f0d2a202c2421632e2220">[email protected]</a>","userName":"bbb","token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNTU5NDk0NTczLCJleHAiOjE1NTk0OTQ4NzN9.XmSHywZv09b4BR9-NxyCTVPF33pLsk3QtTEXQMQF4YHW7i27Ghj2Uh3WZAegpG4rdSImKcm1wMgJsPLpHcTyew","roles":["ROLE_USER","ROLE_ADMIN"]}

If my interpretation is accurate, then perform the following actions -

checkIfIsAdmin(): any {
  let user_string = localStorage.getItem("currentUser");
  const user = JSON.parse(user_string);
  if (user ["roles"]) {
    const roles = user["roles"];
    const index = roles.indexOf("ROLE_ADMIN");
    return index >= 0;
  } else {
    return false;
  }
}

Answer №2

To transform the string into an object, you can utilize JSON.parse(user_string).

Here is a demonstration:

const userData = JSON.parse(user_string);
return userData["roles"].indexOf("ROLE_ADMIN") !== -1;

Answer №3

Consider trying out the following solution:

isAdminUser(): any {
  let user_data = localStorage.getItem("currentUser");
  return !!user_data && user_data.roles.includes('ROLE_ADMIN')
}

//user_data is not defined, result=false
//user_data includes "ROLE_ADMIN", result=true
//user_data doesn't include "ROLE_ADMIN", result=false

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

Utilize browser caching effectively with Firebase and Angular 5 to optimize website performance

After running my Angular 5 website through Google's PageSpeed Insights, it flagged an issue regarding leveraging browser caching. The specific files mentioned were: https://use.typekit.net/####.css (10 minutes) https://www.googletagmanager.com/gtm.js ...

What is the appropriate directory to place the `typescript` package in order for WebStorm to recognize it?

According to the information on this webpage: The Configure TypeScript Compiler dialog box provides two options: Detect: WebStorm will look for a typescript package within the current project. If it finds one, it will use that package. Otherwise ...

How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" ...

Retrieve the Document ID from Firebase

I'm currently exploring the functionality of Firebase and enhancing my workflow with "react-firebase-hooks". Is there a way for me to retrieve both the doc id and doc data simultaneously and pass them as props? Currently, I am only able to access the ...

Error in AngularJs: Unable to assign value to 'showGreeting' property because it is null

Currently, I am utilizing yeoman angularjs-fullstack for project generation. Now, my task is to customize it according to my preferences. I have limited experience with AngularJS and TypeScript, so any feedback would be greatly appreciated, not just the so ...

A guide on how to follow a specific item in an Angular 2 store

I have integrated ngrx store into my Angular2 application. The store reducer contains two objects as shown below: export function loadSuccessNamesAction(state: StoreData, action: loadSuccessNamesAction): StoreData { const namesDataState = Object.assi ...

Compiling the configureStore method with the rootreducer results in compilation failure

Software Setup @angular/cli version: ^9.1.2 System Details NodeJS Version: 14.15.1 Typescript Version: 4.0.3 Angular Version: 10.1.6 @angular-redux/store version: ^11.0.0 @angular/cli version (if applicable): 10.1.5 OS: Windows 10 Expected Outcome: ...

What is the best way to include a Generic type into a functional component's props that also extends a different interface for its props?

Explanation I am currently working on developing a dynamic input form using the FormProvider feature from react-hook-form. const formMethods = useForm<TSongFormData>(); return ( <FormProvider {...formMethods}> <SongInputForm /> ...

Implementing a Map in Typescript that includes a generic type in the value

Here is a code snippet I am working with: class A<T> { constructor(public value: T) {} } const map = new Map(); map.set('a', new A('a')); map.set('b', new A(1)); const a = map.get('a'); const b = map.get(& ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

Changing {number, Observable<string>} to Observable<number, string> is a necessary transformation to be made

Is there a way to convert an array of objects with the following structure: { id: number, data: Observable<string> } into an array of objects with this structure: Observable<{id: number, data: string}> using only RxJS operators? ...

Send properties to the component container

I am currently working on a higher order component that toggles between two children - a component that renders data and a loading component. The challenge I am facing is how to pass the loading state from the data component to the HOC for conditional rend ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Invoke a function in Playwright exclusively when the test title includes a specific @tag

After years of utilizing Selenium, SpecFlow, NUnit, and other testing tools, I have recently delved into Playwright with TS. My goal is to interact with the AzureDevOps API to mark tests as automated only if they contain a specific tag in the test title (e ...

What is the best way to eliminate all spaces in the Zod application?

After reading the Zod documentation, I found that trim only removes whitespace characters at the beginning and end. However, I am in need of a solution to remove all whitespace characters entirely. Here is an excerpt from my current setup (irrelevant code ...

Hiding or showing a div in an Angular 6 component using a service-triggered function

After creating a service with a method that performs an action, the next step is to have this service interact with a specific component. service.ts: doSomething() { // Carries out a task here } In this case, the target component is described below: ...

Unveiling the secret to implementing conditional rendering within a flatlist

I gathered data from an API that provides information on country names and populations. The country names are displayed in a searchable flatlist. My objective is to show a small circle next to each country name in the flatlist based on its population size. ...