An error was encountered while parsing JSON data in Angular due to an unexpected token

I am currently working on implementing role-based authorization in my project. The goal is to hide certain items in the navigation bar based on the user's role. I encountered an error as shown below. How can I resolve this?

service.ts

roleMatch(allowedRoles):boolean{
    var isMatch =false;
    var userRoles:string[]=JSON.parse(localStorage.getItem('userroles')); //the issue occurs here
    allowedRoles.forEach(element => {
      if(userRoles.indexOf(element)>-1){
        isMatch=true;
        return false;
      }
    })
    return isMatch;
  }

component.html

<li *ngIf="Authentication.roleMatch(['Fetch user',
          'add user',
          'edit user',
          'change status',
          'delete user',
          'delete role',
          'Fetch Recuirtmentdetails'])">
          <a  routerLink="/role"class="dropdown-item">User Role</a>
</li>

Answer №1

When looking at the userroles value, it consists of various role permissions such as Fetch user, add user, edit user, change status, delete user, delete role, and Fetch Recruitmentdetails.

This value is in string format and can be parsed using JSON.parse().

To extract the values efficiently, you just need to use var userRoles:string[] as shown below:

var userRoles:string[] = localStorage.getItem('userroles').split(',');

By following this method, you will achieve the desired outcome.

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 the effectiveness of the Ajax Success Handler for retrieving a distinct JSON entity

One of the features I am currently using involves an Ajax command that enables me to query data from a local server. In order to ensure smooth execution, it is crucial for me to return a JSON object through the success handler. The specific structure of m ...

What could be causing the version error when running 'pip install json'?

When attempting to install 'pip install json' in my command prompt, I encountered an error - ERROR: Could not find a version that satisfies the requirement json (from versions: none) ERROR: No matching distribution found for json. What steps shou ...

Unraveling JSON data in AngularJS

After receiving a response from an OData service in JSON format, the data looks like this: [ { "id":1, "ProductName":"Surface Pro 2" }, { "id":2, "ProductName":"iPad" }, ] When att ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Converting a Dataframe or CSV to a JSON object array

Calling all python experts, I have a simple query that needs addressing. Take a look at the data below: 0 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed959691ab9f92d1dcc0c2">[email protected]</a> 1323916902 ...

What is the process for deserializing a string that contains a quote within its value?

I am facing a challenge with deserializing the following string: { "bw": 20, "center_freq": 2437, "channel": 6, "essid": "DIRECT-sB47" Philips 6198", "freq": 2437 } The JSON structure is almost correct, but there is an issue with the quote in t ...

What steps should I take to resolve an Angular error that occurred following the installation of Font Awesome

After installing font awesome, I encountered this error: Uncaught TypeError: Class constructor Platform cannot be invoked without 'new' at Module../node_modules/@angular/cdk/ivy_ngcc/fesm2015/platform.js (platform.js:78) at webpack_require (boo ...

Utilize dynamically generated Java Strings to assign JSON values for effective Karate integration testing in a dynamic manner

For my Karate Integration testing, I am looking to set randomString/randomNumber as Json values instead of hardcoded ones for the payload using the PUT HTTP verb. Additionally, I would like to store these JSON values in a database. ...

What is the best way to modify my if statement to avoid output duplication in my outfile?

When testing for a key, I either do a json.dump if it's present or add it if it's not. Additionally, I check for two other keys and add them if they are absent. I have nested these secondary tests. The issue with the current code is that if the ...

Tips on looping through a dynamic FormControl using Angular2 and FormBuilder

I am facing an issue when trying to iterate over a dynamically generated FormControl in the HTML section. Instead of displaying the expected values, I am getting [object Object],[object Object] in the input field. Here is the provided data structure: { ...

Comparing NativeScript and Flutter

Currently diving into the world of Native Script with Angular, I am fascinated by the code sharing capabilities that allow me to work on both web and mobile applications. However, a lingering question in my mind is why Google chose to develop Angular for ...

Creating a naming convention for constants in Angular schematics

I'm currently working on developing schematics for an Angular service that has a fixed name which cannot be modified by the user. Although I have eliminated all references to the 'name' variable, I encounter an error when attempting to util ...

SyntaxError: Unexpected token '<' in Angular 6

I have been working on an angular website project. Here is the package.json file for my production environment: "dependencies": { "@angular/animations": "^5.0.2", "@angular/cdk": "^5.1.0", "@angular/common": "^5.0.2", "@angular/compiler": ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

The usage of @Inject('Window') in Angular/Jasmine leads to test failures, but removing it results in code failures

Currently, I am encountering a dilemma related to using Angular's @Inject('Window') within a web API service. This particular issue arises when the Window injection is utilized in the service constructor, leading to test spec failures in the ...

Issue with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

Issue: Formcontrolname attribute is undefined causing TypeError when trying to retrieve 'get' property.Remember to define formcontrolname attribute to

Having trouble creating a form at the moment and keep encountering this error: 'ERROR TypeError: Cannot read property 'get' of undefined' Even after trying various solutions like using formControlName in brackets or accessing the va ...

Mastering checkbox selection in Angular reactive formsLearn how to effortlessly manage the checked status of

I am struggling with setting the checked status of a checkbox control within an Angular reactive form. My goal is to change the value based on the checked status, but it seems like the value is controlling the status instead. For instance, I want the for ...

How can I obtain the model values for all cars in the primary object?

const vehicles={ vehicle1:{ brand:"Suzuki", model:565, price:1200 }, vehicle2:{ brand:"Hyundai", model:567, price:1300 }, vehicle3:{ brand:"Toyota", model ...

When attempting to call methods after executing a new Class in Android Studio, the application crashes

I have been working on an app that utilizes JSON data. The issue I am facing is that when I retrieve the JSON using HentData.execute() and assign it to a string variable, my program crashes when I try to perform any operations with it. HentData extends As ...