Home:ALL Converter>Use token from local storage in HTTP request in Ionic 2

Use token from local storage in HTTP request in Ionic 2

Ask Time:2017-02-11T00:46:55         Author:almo

Json Formatter

My Ionic 2 app has a login and it stores the auth token to the local storage. Then I want to use this token in my HTTP requests.

In my auth service I have the following method:

authToken() {
      return this.storage.get('auth_token').then((val) => {
         return val;
      });
    }

And then in my service that makes the HTTP request I have:

export class Rides {

    token: string;

    constructor(public http: Http, public authentification: Authentification) {
        this.authentification.authToken().then((val) => {
            this.token = val;
            console.log(this.token);
        });
    }

    getOpenRides() {
        var headers = new Headers();
        headers.append('Authorization', 'Token token=' + this.token);
        return this.http.get('URL', { headers: headers })
        .map(res => res.json());
    }

}

It logs the correct token in my Rides service constructor. But then when I use the token in the HTTP request my server says that token=undefined was sent.

What do I have to do different?

This is the page component where I call getOpenRides and where I want to display the result:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Rides } from '../../providers/rides';

/*
  Generated class for the Agenda page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-agenda',
  templateUrl: 'agenda.html',
  providers: [Rides]
})
export class AgendaPage {

    openRides: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public rides: Rides) {}

  ionViewDidLoad() {
    this.openRides = this.rides.getOpenRides()
    .subscribe(response => { console.log(response.rides) });
  }

}

Author:almo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/42164524/use-token-from-local-storage-in-http-request-in-ionic-2
yy