How to extract a value from [object object] in Angular4

In my previous question, I shared the code below:

getUserRole() {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${this.getToken()}`);
  console.log(this.getToken());
  const options = new RequestOptions({ headers: headers});

  return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options).pipe(map(res => res.json()))
    .subscribe(data => {
      this.userRole = JSON.stringify(data);
      if (this.userRole === 'parent') {
        this.logout();
      } else if (this.userRole === 'school') {
        this.isUser = true;
        this.isAdmin = false;
        this.cookieService.set('isSchool', '1');
      } else if (this.userRole === 'admin') {
        this.isUser = false;
        this.isAdmin = true;
        this.cookieService.set('isAdmin', '1');
      }
    });
}

After calling this function, trying to access userRole results in undefined, possibly because it gets returned before .subscribe is executed.

This leads to undefined being logged here:

var result = this.getUserRole(token);
console.log('Call from login ' + result);

To address this issue, I modified the approach like so:

getUserRole(roletoken: string) {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${roletoken}`);
  const options = new RequestOptions({ headers: headers});
  var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).pipe(map(res => res.json()));
  console.log(result);
  return result;
}

However, this change causes result to be displayed as [object object].

I am seeking guidance on which method should be used to promptly assign the value of userRole using either approach.

The data received from the API looks like this:

["school"]

This is how the function is called:

this.getUserRole(token);
console.log('Call from login ' + this.userRole);

Within the getUserRole function:

var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).subscribe(data => {
  this.userRole = JSON.stringify(data);
  console.log(data);
});

Here is the order of console outputs achieved:

Call from login undefined

Response {_body: "["school"]", status: 200, ok: true, statusText: "OK", headers: Headers, …}

Even with using subscribe, the assignment of userRole is happening later when called from login.

Answer №1

ObtainUserRole returns an Observable. To make the HTTP call and receive the data, you must subscribe to it. Since you are using the older Http instead of HttpClient, you need to convert the response to JSON data. The following code snippet should help:

getUserRole(roletoken: string) {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${roletoken}`);
  const options = new RequestOptions({ headers: headers});
  return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).pipe(map(response => response.json()));
}

It's crucial to comprehend the asynchronous behavior of Observables and HTTP requests. this.userRole is assigned a value only after the request is completed. Therefore, if you wish to work with this.userRole and ensure that it holds a value, use it within the subscribe function like this:

this.getUserRole(token).subscribe(userRole => { 
  this.userRole = userRole;
  console.log('Call from login ' + this.userRole);
});

Answer №2

if I were to handle it differently, when receiving a JSON response from your REST API

    userRole: UserRole // setting the type of userRole as previously defined
    getUserRole() {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${this.getToken()}`);
  console.log(this.getToken());
  const options = new RequestOptions({ headers: headers});
  return this.http.get<UserRole>(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options)
  .subscribe(data => {
  this.userRole = data;
    if (this.userRole === 'parent') {
      this.logout();
  } else if (this.userRole === 'school') {
    this.isUser = true;
    this.isAdmin = false;
    this.cookieService.set('isSchool', '1');
  } else if (this.userRole === 'admin') {
    this.isUser = false;
    this.isAdmin = true;
    this.cookieService.set('isAdmin', '1');
  }
  });

}

In case the API returns a list of JSON objects (e.g., [{name: 'name', first_name:'first_name'}])

    userRole: UserRole // setting the type of userRole as previously defined
    getUserRole() {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${this.getToken()}`);
  console.log(this.getToken());
  const options = new RequestOptions({ headers: headers});
  return this.http.get<UserRole[]>(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options)
  .subscribe(data => {
  this.userRole = data[0];
    if (this.userRole === 'parent') {
      this.logout();
  } else if (this.userRole === 'school') {
    this.isUser = true;
    this.isAdmin = false;
    this.cookieService.set('isSchool', '1');
  } else if (this.userRole === 'admin') {
    this.isUser = false;
    this.isAdmin = true;
    this.cookieService.set('isAdmin', '1');
  }
  });

}

If the API response is not in the form of proper JSON like ['school'] but rather something different

    getUserRole() {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${this.getToken()}`);
  console.log(this.getToken());
  const options = new RequestOptions({ headers: headers});
  return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options).pipe(map(res => res.json()))
  .subscribe(data => {
  this.userRole = JSON.stringify(data[0]);
    if (this.userRole === 'parent') {
      this.logout();
  } else if (this.userRole === 'school') {
    // same 

}

or

    getUserRole() {
  const headers = new Headers();
  headers.append('Authorization', `Bearer ${this.getToken()}`);
  console.log(this.getToken());
  const options = new RequestOptions({ headers: headers});
  return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options).pipe(map(res => res.json()))
  .subscribe(data => {
  this.userRole = JSON.stringify(data);
    if (this.userRole[0] === 'parent') {
      this.logout();
  } else if (this.userRole[0] === 'school') {
    // same but you take the first element of the list

}

While I typically receive JSON responses from my APIs, these are steps I would consider initially and debug accordingly using browser tools like Chrome debugger.

Remember, debugging can help track variable values at each step by setting breakpoints in your function and following them through ;)

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

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

Encountering Issues with Python Data Serialization

I encountered an issue while attempting to convert a dictionary object into a Json string using my python code. The error message that was thrown is as follows: SerializationError: ({'status': 'rd', 'name': 'Detecci&bso ...

Vue.js is unable to recognize this type when used with TypeScript

In my code snippet, I am trying to set a new value for this.msg but it results in an error saying Type '"asdasd"' is not assignable to type 'Function'. This issue persists both in Visual Studio and during webpack build. It seems like Ty ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...

Search input in real-time

I am in the process of implementing a live search input feature in Ionic 3 within a form group. Within my TypeScript file, I have the following code: getSubElements(selectedValue) { if(selectedValue){ this.VisitesProvider.getEcolesLi ...

How to Trigger Child Component Functions from Parent Methods in Angular 8

I am struggling to call a child component method from my parent component and pass an object. When I try to do so, I encounter the following error: Cannot read property 'RunMe' of undefined What am I missing? Child component: runMe = (item) =& ...

Ngb-xx is not a recognized chemical property

Attempting to implement ngb bootstrap in my Angular project has been challenging. Errors keep popping up for every ngb component I try to use. https://i.sstatic.net/jF1xV.png Here's a glimpse of my package.json: https://i.sstatic.net/utqX6.png and ...

Check for the data attributes of MenuItem in the TextField's onChange event listener

Currently, I am facing a situation where I have a TextField in select mode with several MenuItems. My goal is to pass additional data while handling the TextField's onChange event. I had the idea of using data attributes on the MenuItems for this pur ...

Parsing JSON to Transform ID into Object

Ensuring efficient data transfer in my RESTful web service, I serialize only the ID of nested objects to avoid redundancy (for example, a Message's User creator only has userId serialized as both client and server already have the user details). The ...

Issue with separatorKeys functionality in ng2-tag-input

I've been experimenting with the ng2-tag-input module using a simple configuration: import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'search-form', template: `<tag-input [( ...

Tips for simulating behavior in express using Typescript and the Mocha library

Help with mocking 'Request' in Mocha using express with Typescript needed! Here is the current approach: describe("Authorization middleware", () => { it("Fails when no authorization header", () => { const req = { ...

There is an error appearing in my .ts code: [ts] The property 'name' is not found in type 'any[]'

While my coding is working fine and data is showing on the page, there seems to be an error occurring in the VSE editor. It is showing something like this: [ts] Property 'name' does not exist on type 'any[]'. This is a snippet of my ...

Customize your Bootstrap panel with a user-friendly wysiwyg editor

I'm trying to adjust the height of a wysiwyg editor housed within a panel to be 200px. How can I achieve this? <div class="row"> <div class="col-xs-12 col-md-12 col-lg-8"> <panel heading="Product Des ...

Utilizing ngFor in Angular to iterate through an array and retrieve the count of elements while displaying their

I utilized the following angular functions to display the data: availableLockers = [ { "lockerCode": "L01", "allocStatus": "alloc" }, { "lockerCode": "L02", &qu ...

steps to replicate a successful AJAX call performed by a curl command

I've successfully captured a request using Charles Proxy with curl, which returns JSON data. I've been struggling all day to convert this into an AJAX call without success. I'm passing a token in the header to access the JSON service. { "ca ...

JSON Schema Validator succeeds even with problems

My objective is to construct a schema that includes an array of items, each with a "key" string property that determines changes in the "data" property schema. Here is the schema I am using for validation and the JSON data that I anticipate failing valida ...

"Learn how to programmatically close all panels in an ngb-accordion component in Angular 2 Release 6, leaving only

I have recently begun working on an accordion and I am trying to figure out how to make the first panel expand while keeping the others closed. I attempted to use [closeOthers]="true" but it doesn't seem to be effective. Here is my HTML code: <di ...

Prevent user input with Angular ng-pick-datetime when a specific condition is met

I'm currently developing a project using Angular 8 and incorporating the ng-pick-datetime plugin. I have encountered a requirement to dynamically disable both the date time picker and the input element that triggers it based on a specific condition. D ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...