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

When trying to search for 'elForm' using the 'in' operator within the context of a "datetime" type, the error "Unable to find 'elForm' in undefined" occurs

I am attempting to implement a datepicker with time options from Element UI. I am encountering an issue within the ElementUI component. It functions correctly if the type option is set as date, but throws an error with datetime. Below is my code snippet an ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

Update the content of the text box when the button is clicked

How can I make the text box value appear only when a button is clicked? See the code snippet below: HTML: <input type="text" [(ngModel)]="serverName"> <button class="btn btn-primary" (click)="onAddClk">Add</button> TS File: onAddClk( ...

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

Setting up Angular on your Mac

Recently, I attempted to set up Angular on my macOS system. After confirming that I have npm 5.6.0 and node 8.11.1 installed, I proceeded with sudo npm install -g @angular/cli. It appeared to be successful at first, but upon running ng --version, the follo ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

Duo and reference loop

I'm trying to learn how to use backreferences in JavaScript. I have an array and want to replace it within a string. Here's what I've attempted so far: var items = ["book", "table"]; var sentence = "The $1 is on the $2"; var newSentence ...

Embarking on the journey of transitioning code from server-side to client-side

Currently, I am looking to transition the code behind section of my asp.net web forms application to client-side ajax or javascript - still deciding on which route to take. The main goal for this change is to ensure that the application remains functional ...

I'm attempting to utilize AJAX to modify the sorting and ordering arguments in a WP_Query, yet I'm struggling to pinpoint the reason behind the failure of my code

After hours of non-stop work, about 6 solid hours with no breaks, I am baffled as to why this code isn't working. Let's take a look at the form in question: <div id="wp-ajax-filter-search" class="full"> <form ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...

Troubleshooting deployment issues of an Angular 5 and ASP.NET Core 2.1 application on an nginx server

Trying to get my Angular 5 application deployed on Digital Ocean Ubuntu 16.4 Nginx, but running into some issues. I can successfully access the API endpoints: http:://ipaddress/api/values However, I am facing problems with the Angular website itself: T ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Protecting Node.js Files

As I prepare to embark on creating a new website, my main goal is to collect form input values such as dropdowns and radio boxes from the client without requiring user accounts. These values will be used for sensitive calculations, making security a top pr ...

What is the best way to neatly import multiple images in Next.js?

I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...

Efficiently converting arrays to strings in JavaScript using mapping techniques

My goal is to retrieve data through AJAX without formatting it as JSON, so I took the initiative to encode it myself. The data I am working with consists of client records: where the pound sign (#) separates the client records, the pipe sign (|) separates ...

Creating a stream of observables in RxJs and subscribing to only the latest one after a delay: A comprehensive guide

I am trying to create a stream of Observables with delay and only subscribe to the last one after a specified time. I have three HostListeners in which I want to use to achieve this. I would like to avoid using Observable form event and instead rely on H ...

What is the best way to iterate over an array of objects?

I have an Array of Objects that I need to use in order to create an HTML Table: Array(5) 0: Object id: 4 name: Sand Jane address: Green Sand Street ... ... ... 1: Object 2: Object ... ... ... Currently, I am able to perform a search wit ...

In PHP forms, ensure that only completed textboxes are submitted and empty textboxes are discarded

I've created a form that displays all available products from a database along with their prices. Users can input the quantity they want to purchase for each product, and upon submission, the total amount will be calculated. There are 5 products in th ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Exploring Node JS Express Thread Clarity

Having recently delved into the world of node js, I've familiarized myself with its architecture. I grasp the concept of the event loop, the main thread (V8 engine thread), and the other threads handled by libuv. When the main thread needs to handle ...