Issue: JSON parsing error due to unexpected token 'u' at the beginning of the JSON

I'm encountering an issue with my TypeScript code:

SyntaxError: Unexpected token u in JSON at position 0:

Upon checking the browser console, I found this error message: https://i.sstatic.net/mk2Z4.png

Here's the problematic TypeScript code:

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

Another incorrect part of the code:

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): boolean {
  if (localStorage.getItem('userToken') != null) {
    let roles = next.data["roles"] as Array<string>;
    if (roles) {
      var match = this.userService.roleMatch(roles);
      if (match) return true;
      else {
        this.router.navigate(['/forbidden']);
        return false;
      }
    }
    else
      return true;
  }
  this.router.navigate(['/login']);
  return false;
}

Answer №1

According to user184994, it seems that the code

localStorage.getItem('userRoles')
is returning undefined.

The error message "SyntaxError: Unexpected token u in JSON at position 0" indicates that the JSON parser encountered the letter u at the beginning of the data, causing a parsing failure.

It is important for the data to be in a valid JSON format.

To resolve this issue, you can initialize userRoles as an empty array like so:

var userRoles = [];
var userRolesStr = localStorage.getItem('userRoles');
if (userRolesStr) {
  userRoles = JSON.parse(userRolesStr);
}

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

Angular Material 2 Boot-Up Spinner

Just getting started with Angular 2 and I am using the angular-cli to create my app. I am looking to incorporate the Progress Spinner component into my project from the beginning, but I have been having trouble finding information on how to do so. I know ...

Expanding and collapsing all elements with Angular Bootstrap 4's collapse feature

How can I make only one item in my ngFor expand and close using the Bootstrap 4 collapse component? This is the code implementation: <div class="card-footer account clickthrough" *ngFor="let attachment of item.attachments; let j=index" (click)="isColl ...

md-table Using FirebaseListObservable as a DataSource

I am currently working with a FirebaseListObservable and a BehaviorSubject that is listening for an input filter. The goal now is to merge these two entities in order to return an array that has been filtered based on the input value, which will then be us ...

The canActivate: [AuthGuard] feature on the external router is not functioning as expected

I'm encountering an issue with my routing. I attempted to use the following code: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [AuthGuard], children: [ { path: 'events', component: Ev ...

Prevent selection of future dates in Kendo UI Calendar Widget

Can someone please advise on a method to disable future dates (i.e., gray them out) in the Kendo UI Calendar widget? I've attempted hiding the future dates, but it doesn't look good. I've also tried different ways to gray them out without su ...

Errors in type checking observed in app.reducer.ts file for Angular NgRx

I encountered an issue with my login/logout state management setup. The error message I received is as follows: When trying to assign '(state: State | undefined, action: authActions) => State' to type 'ActionReducer<State, Action>& ...

Tips for restricting the signature within a function depending on the argument's value

Trying to consolidate interface methods into a single function with an additional operation parameter. The function can be called as expected, but struggling to narrow the signature within the function. Found some assistance in this SO post, but still enco ...

The TypeScript factory design pattern is throwing an error stating that the property does not

While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error. Here is the structure of my ...

The property 'brews' must be assigned a value either in the constructor or with an initializer

After attempting to launch my project, I encountered an error. I have attempted to resolve this issue by setting strictPropertyInitialization to false in angularCompilerOptions without success. Additionally, I tried using the ! operator instead of brews ...

What is the proper way to conduct unit testing on a function that is invoked in a service's constructor

Is there a way to verify, within the service's spec file, that a function is invoked in the constructor? Consider the following example: @Injectable({ providedIn: 'root' }) export class myService { constructor() { this.myF ...

Tips for displaying an object's properties using ngfor?

<div *ngFor="let article of articleList; let i = index"> <div class="item"> <div class="image-holder" style="background-image: url(https://uniqueblog.com/images/ninja-1.jpg)"&g ...

Angular: Variable `app` has not been defined

I am working on a simple MEAN stack app and it is almost up and running, but I encountered an uncaught reference error when it tries to redirect to the index page. The server seems to be running fine and the browser displays "Loading..." as expected on the ...

Troubles arise with a Web API ASP .NET / Angular2 Session hosted on Azure

Hello, this is my first question here so please let me know if something doesn't fit. Currently, we are working on developing a Web API using C# and Angular2. One of the features requires the session to be efficient, but despite going through numerou ...

Error in Angular 16.2.0: Signal TypeError <mySignal> cannot be executed as a function

I have a service that has a signal containing a list of Customers (interface). Whenever I call a method to retrieve the signal content, I encounter an issue: ERROR TypeError: this.customers is not a function at Object.upsertCustomer [as next] Here is th ...

What is the process for defining child routes in Angular 2.0 for Dart?

When working with TypeScript, a child route can be easily defined as shown below: export const routes: Routes = [ { path: '', redirectTo: 'product-list', pathMatch: 'full' }, { path: 'product-list', component: P ...

Encountering the ObjectUnsubscribedErrorImpl while utilizing angular datatable with angular version 7

I am encountering an issue when trying to display a DataTable in a modal window. Initially, everything works as expected and I can see the screen perfectly. However, after closing the modal window and opening it again, the DataTable no longer shows the sea ...

There are two distinct build commands in Angular that can produce unique JS file hashes

I'm currently working on a new Angular project where I have two different npm commands specified in my package.json. Both of these commands run ng build --output-path=..., but with different flags to generate build files in separate locations. Is the ...

react - Arrow body should not be enclosed in a block statement

I am working with an array const reportOptions = [ { id: 1, title: 'Report', }, { id: 2, title: 'Report 2', }, { id: 3, title: 'Report 3', }, ] My goal is to create a new state as shown be ...

I attempted to populate a ng material data table using a schematic, but struggled to successfully replace the dummy data with information from an API

This code snippet defines the Tickets[] interface: export interface Tickets { name: string; id: number; } It also includes a service created to fetch data from an API. Currently, the data is hardcoded in the getData() function, but it needs to ...

The error that has occurred is: `TypeError: The object on the right side of the 'instanceof' keyword is

Testing my function that verifies if a variable is an instance of a specific type and performs an action has been successful. I conduct the verification using the following code: myCheckingFunction = () => { if (target instanceof H.map.Marker) { ... ...