Ad

Angular Can't Set Value To Public Variable

- 1 answer

I am trying to set value form localStorage() into my variable and use that variable in functions but the variable comes 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);  // see screenshot below
    }).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);  // see screenshot below
    console.log('my headers ', headers);  // see screenshot below
    return this.http.get(this.env.Dashboard + '/dashboard', {headers})
    .pipe(
      tap(data => {
        console.log(data);
      })
      );
    }
}

Screenshot

one

another issue is my request header sends 2 values in header instead of 3 (not sure if it's because of token being undefined or not)

two

it supposed to send Accept,Content-Type,Authorization instead only sent Accept and Content-Type

Any idea?

Update

this is my component that I call my service 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;
    });
  }

}
Ad

Answer

SOLVED

I'd to change both services and component file to get my data, here is my final code

services

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

component

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

    await this.loading.present();

    this.dashboardService.getDashboard().subscribe((res) => {
      for (const school of res.data) {
        this.schools.push(school);
      }
      this.hideLoading();
    });
  }

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

now my page loads include my data with proper loading screen.

hope it help others as well.

Ad
source: stackoverflow.com
Ad