【发布时间】:2017-02-10 16:46:55
【问题描述】:
我的 Ionic 2 应用程序有一个登录名,它将身份验证令牌存储到本地存储中。然后我想在我的 HTTP 请求中使用这个令牌。
在我的身份验证服务中,我有以下方法:
authToken() {
return this.storage.get('auth_token').then((val) => {
return val;
});
}
然后在我的服务中发出 HTTP 请求:
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());
}
}
它在我的 Rides 服务构造函数中记录正确的令牌。但是当我在 HTTP 请求中使用令牌时,我的服务器说 token=undefined 已发送。
我有什么不同的?
这是我调用 getOpenRides 并希望显示结果的页面组件:
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) });
}
}
【问题讨论】:
-
您在何时何地调用
getOpenRides函数? -
我在要显示开放游乐设施的页面组件中调用它。我将其添加到我的问题中。
-
嗯,我假设您在另一个组件中设置了身份验证令牌?如果是这种情况,问题应该出在组件中的
providers: [Rides]上。无论您在组件中声明提供者的何处,都意味着它是一个新的服务实例,因此它无法访问由另一个组件和服务设置的属性。尝试在您的 ngModule 中添加providers: [Rides, AuthService],并从组件中删除单个提供程序。这意味着该模块中的所有组件都使用 same 服务并且可以访问从其他组件设置的变量。
标签: angular ionic-framework ionic2