Angular: Extracting a String from an Observable of any Data Type

Currently, I have a backend REST service that is responsible for returning a string:

@GetMapping("/role/{id}")
    public String findRole (@PathVariable("id") String username) {
    User user = userRepository.findByUsername(username);
    return user.getRoles().get(0).getName();

    }

I am attempting to retrieve this string and utilize it in an Angular .ts file. Here is my service code:

getRole(name: string): Observable<any> {

    return this.http.get('http://localhost:8080/api/role/' + name);

  }

This is my .ts code:

login(){
    this.loginService.authenticate(this.credentials,()=>{

     this.loginService.getRole(this.credentials.username).subscribe(
      data => {
      this.role=JSON.stringify(data);
   });

      if (this.role == "ROLE_ADMIN" )
          { this.router.navigateByUrl('/home/(contentOutlet:product)');}

          else console.log(this.role);
          /*
      else 
      { this.router.navigateByUrl('/home/(contentOutlet:dashboard)')}*/
    })

  }

However, I am encountering the following error:

"Unexpected token R in JSON at position 0"

Answer №1

Initially, there are a few mistakes in the code you provided:

login(){
    this.loginService.authentificate(this.credentials,()=>{
        this.loginService
               .getrole(this.credentials.username)
               .subscribe(data => {
                  this.role = data // No need to stringify, assuming your response is already in text format
        });

      // The condition below will always return false as this.role is still undefined
      if (this.role === "ROLE_ADMIN")
         this.router.navigateByUrl('/home/(contentOutlet:produit)');
      else 
         console.log(this.role);
    })

  }

Firstly, the error message

Unexpected token R in JSON at position 0
occurs because of your usage of JSON.stringfy(), which expects a JSON object but receives a string from your backend, leading to an error.

Furthermore, when checking the value of this.role, it won't be assigned until the API response is received. To address this, adjust your code as follows:

.subscribe(data => {
    this.role = data;
    // At this point, ensure that the role holds the expected value
    // TODO: <-- INSERT THE CODE DEPENDENT ON "ROLE" HERE
});

Answer №2

Successfully resolved the issue. I needed to specify the return type as follows: {responseType: 'text'}

Updated version of my service:

    getRole(name: string): Observable<any> {

        return this.http.get('http://localhost:8080/api/role/'+name,{responseType: 
   'text'});

      }

No need to utilize JSON.stringify anymore, assigning data directly to this.role is the correct approach.

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

Is it possible to dynamically adjust the container size based on its content with the help of *ngIf and additional directives?

I have a single-image container that I need to resize when editing the content. The size should adjust based on the incoming content. See the images of the containers below: Image 1: This is the container before clicking on the edit button. https://i.sst ...

What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

Cannot see the template on the Angular Typescript component

After encountering and resolving this issue: AngularJS directive not displaying the template I decided to experiment with an Angular component and TypeScript, but unfortunately, I can't seem to make it work. The component refuses to display. This is ...

What sets apart the states of the select tag from other input tags in Angular?

I am having trouble displaying an error message for a select tag when it is in a touched state. The error handling seems to be working fine for other input tags, but not for the select tag. Below is the code snippet: <div class="form-g ...

Encountering issues while trying to update npm in a Angular 6 project

Attempting to upgrade npm from version 6.1.0 to 6.4.0 using the command line interface: npm install -g npm Unfortunately, encountered an error during the update process. npm ERR! path /usr/local/lib/node_modules/npm/node_modules/ansi-regex npm ERR! co ...

Experience the power of combining React with typescript, webpack, and ui-router-react for

After carefully studying the ui-router-react documentation (), I am encountering several challenges with webpack compilation when importing import {UIRouter, UIView, UISref, UISrefActive, pushStateLocationPlugin} from 'ui-router-react'; This is ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

Combining Interfaces in Typescript: Utilizing Union Types with a Base and Extended Interface

I'm facing an issue with the following code snippet interface BaseA { a: number; } interface SpecialA extends BaseA { b: number; } type A = BaseA | SpecialA const a = { a: 5, b: 5 } as A console.log(a.b) Even though I thought the code was ...

What is the proper way to utilize environment variables on Heroku for my Angular application?

Currently, I am facing difficulties setting up environment variables (or Config Vars in the Heroku world) such as production=true for my angular app on Heroku. I'm struggling to configure the postinstall and build scripts to make use of them effective ...

HTTP POST request is being blocked due to cross-origin request

My angular client app is sending http requests to a .NET core web API, but I'm encountering a CORS error even though I have enabled CORS. Interestingly, GET requests to my SearchController work fine without any issues, but when it comes to sending a P ...

Convert a regular element into a DebugElement within an Angular framework

Recently, I was working on testing an Angular Component which was going smoothly until I encountered a challenging issue that has been perplexing me for days. My main objective was to test whether the method "ajouterCompteurALaCampagne" is being called whe ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...

Having trouble logging in with Google using React, Redux, and Typescript - encountered an error when attempting to sign in

As a beginner in TS, Redux, and React, I am attempting to incorporate Google Auth into my project. The code seems functional, but upon trying to login, an error appears in the console stating "Login failed." What adjustments should be made to resolve thi ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

Ensure your TypeScript class includes functionality to throw an error if the constructor parameter is passed as undefined

My class has multiple parameters, and a simplified version is displayed below: class data { ID: string; desp: string; constructor(con_ID:string,con_desp:string){ this.ID = con_ID; this.desp = con_desp; } } When I retrieve ...

Angular attribute directive accesses a sibling attribute reference

Attempting to create an attribute directive named pagingContext that will work alongside the angular material sort directive matSort. The concept is to have an element structured like: <table matSort [pagingContext]="pagingContext"> With a directi ...

Unit test does not show the PrimeNG menubar start directive

Currently, I am in the process of writing Jasmine tests for my component which includes PrimeNG's menubar. Within this component, I am utilizing the start template directive in the following manner: <p-menubar id='menubar' [model]='i ...