Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined.

code

export class DashboardService {

  public token: any;

  constructor(
    private env: EnvService,
    private http: HttpClient,
    private storage: NativeStorage
  ) {
    this.storage.getItem('token').then((token) => {
      this.token = token.access_token;
      console.log('storage token ', token.access_token);  
    }).catch(error => console.error(error));
  }

  getDashboard() {
    const headers = new HttpHeaders({
      Accept: 'application/json, text/plain',
      'Content-Type': 'application/json',
      Authorization: this.token
    });
    console.log('my token ', this.token);  
    console.log('my headers ', headers);  
    return this.http.get(this.env.Dashboard + '/dashboard', {headers})
    .pipe(
      tap(data => {
        console.log(data);
      })
    );
  }
}

Screenshot

https://i.stack.imgur.com/hSRN6.png

Another problem I encountered is that my request header only sends 2 values instead of 3 (not sure if it's due to the token being undefined or not).

https://i.stack.imgur.com/YVRNf.png

It should be sending Accept,Content-Type,Authorization but it only sends Accept and Content-Type.

Any suggestions?

Update

This is the component where I am utilizing the service mentioned above:

export class DashboardPage implements OnInit {

  schools: any = [];

  constructor(
    private authService: AuthenticationService,
    private menu: MenuController,
    private dashboardService: DashboardService
  ) {
    this.getSchool();
  }

  ngOnInit() {
    this.menu.enable(true);
  }

  logout() {
    this.authService.logout();
  }

  getSchool() {
    this.dashboardService.getDashboard().subscribe((res) => {
        this.schools = res;
    });
  }

}

Answer â„–1

RESOLVED

In order to retrieve the data, I had to make modifications to both my services and component files. Below is the final code snippet:

services

getDashboardData(): Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: this.token.access_token
      })
    };
    return this.http.get(`${this.env.Dashboard}` + '/dashboard', httpOptions).pipe(
      map(response => response)
    );
  }

component

async fetchSchoolData() {
    this.loading = await this.loadingController.create({
      message: 'Loading...',
      spinner: 'dots',
      duration: 3000
    });

    await this.loading.present();

    this.dashboardService.getDashboardData().subscribe((result) => {
      for (const school of result.data) {
        this.schools.push(school);
      }
      this.hideLoader();
    });
  }

  private hideLoader() {
    this.loading.dismiss();
  }

Now, my page successfully displays the requested data along with a proper loading screen.

I hope this solution proves helpful to others facing similar issues.

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

Using Vaadin: update Label text with TextField input after Button is clicked

I'm working on a simple Vaadin form where I want the text entered in a TextField to appear in a Label after the user clicks on a Button. Here's the code snippet: package com.example; import javax.servlet.annotation.WebServlet; import com.vaad ...

Transforming .POST into corresponding .AJAX techniques

I'm currently attempting to convert a .post javascript call into an equivalent .ajax call in order to make it asynchronous. However, I'm running into some issues and can't seem to get it to work. The original working .post call looks like th ...

Discover the inverse of Object Arrays interaction in TypeScript

My agent object has the following structure: agentObj = { "agentId": "saqib", "attributes": [ { "name": "Marketing", "type": "Boolean", }, { "name": "English", "type": "Profi ...

Is there a way to convert arrow functions in vue files through transpilation?

I have developed a Vue application that needs to function properly in an ES5 browser (specifically iOS 9). One issue I've encountered is that some of the functions within the Vue components are being transformed into Arrow functions: ()=>, which i ...

Displaying time in weekly view on the Angular 4.0 calendar

I've integrated the library into my Angular application to manage calendar events display and creation. The app features a monthly, weekly, and daily view option for users. However, I noticed that in the weekly view, only the dates are shown without ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...

Running a Jest test that triggers process.exit within an eternal setInterval loop with a latency of 0, all while utilizing Single

In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrap ...

AmCharts Axis renderer mistakenly renders an additional grid line

I have successfully created a basic XYChart using amcharts4. To get rid of the grid lines on the x-axis, I changed the stroke opacity for the x-axis grid to 0 using the following code: xAxis.renderer.grid.template.strokeOpacity = 0; Everything was workin ...

Which child node of the html tag represents the "text"?

In my quest for answers, I have searched extensively but to no avail: As we all know, when a web page is loaded in a browser, it generates a tree-like structure called the Document Object Model (DOM). This allows Javascript to manipulate the elements of t ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

Convert the canvas to an image by right-clicking

Is it possible to treat the canvas element as an image when using drawImage() to draw on it? When I attempt to right click on the canvas element that has been drawn on, the option "Save image as" does not appear. The right click menu displays: What step ...

Is it possible for me to create a CSS class based on a condition using [ngCLASS]?

I am struggling with logic writing in my Angular2 project. On a HTML page, I have two buttons - YES and NO that I want to style with different colors. I have set up a condition in the div tag like this: ngClass="'result'?'yes':' ...

Maximize the performance of displaying images

At the moment, I have a set of 6 graphics (0,1,2,3,4,5)... The arrangement of these graphics looks fantastic! However, I am facing an issue when a user only has 3 graphics, for example 0, 2, and 5. In this scenario, my graphics do not line up correctly. D ...

ng-for loop not properly rendering array of collections in table cells

I've been working on developing a MEAN Stack application that deals with mongoDB data related to hostels. hostels { "_id" : ObjectId("5e3c21c03d8d54b35af796ed"), "Hostel" : "The traveler's Lodge", "Rooms" : 23, "Customer" : [ { ...

When a custom header is added, cookies are not included in cross-origin jQuery AJAX requests

An issue arises when sending an ajax request from our main domain to a subdomain (cross-origin) through jQuery. Despite having CORS implemented and functional, we encounter a problem when attempting to include a custom header in the request. The presence o ...

Error during Ng 16 upgrade - npm ERR! Peer dependency conflict found: @angular/[email protected]

I am currently in the process of upgrading my Angular version from 11 to 16. While this Angular documentation has been quite helpful, I am encountering various errors and challenges. Let me provide you with the versions I am working with: Angular CLI: 11. ...

Error message: Unknown scope- unable to process 'files-path' Android File provider issue

My current project involves implementing file system access in react native Android. However, when attempting to add 'files-path' in XML, an error stating "Error: Unsupported type 'files-path'" is encountered. I am utilizing the react n ...

How to utilize jQuery to eliminate HTML onchange code

This block of code features an HTML onchange attribute as well as the use of jQuery's change event on an input text. I want only the jQuery change event to take precedence. I have attempted to use both unbind and off without success. Can someone prov ...