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) });
}
}