我有一个自定义http服务,它将访问令牌附加到每个请求,我想使用来自ionic2存储值的访问令牌
这是我前两个问题的代码
所以在httpclient服务中我有
@Injectable()
export class HttpClient {
authtoken: string;
storage: Storage;
constructor(private http: Http, storage: Storage, private _authService:Authservice) {
this._authService.tokenEvent.subscribe(res => { //subscribing to token event in authservice
if (res) {
this.storage.get('token')
.then(token => {
this.authtoken = token
});
}
})
}
get(url){
let headers = new Headers();
this.createGeneralHeaders(headers);
return Observable
.flatMap( //retuns an error flatmap doesnt exist on observable
name => this.http.get(`${url}?access-token=${this.authtoken}`, {headers})
);
}
在authservice中设置令牌
tokenEvent: Subject<any> = new BehaviorSubject(null);
login(user: UserModel): Observable<any> {
return this._http.post(this.loginurl + "mobile-login", body)
.map((response: Response) => {
let token = response.json().access_token;
if (token) {
this.storage.set('token', token).then(res => this.tokenEvent.next(true));
return true;
}
})
//.catch(this.handleError);
}
现在我可以在任何http请求中轻松使用来自第一个服务的get,例如
getChecklists(truckid): Observable<any> {
return this._httpclient.get(this.inspectionurl + "get-checklists")
.map(res=>res.json().data)
}
上述第一个服务返回了flatmap不存在的错误。如何调整要在另一个http请求中使用的第一个服务,还要附加令牌事件中的令牌
这两个解决方案基于this question和this question
答案 0 :(得分:2)
我不认为你需要一个平面图,请看这个链接:
http://reactivex.io/documentation/operators/flatmap.html
只有当您的回复是可观察的并且您想要合并流时,您才会使用它,我认为这不是您的目标。
所以你的&#39;得到&#39; HttpClient上的函数将变为:
get(url){
let headers = new Headers();
this.createGeneralHeaders(headers);
return this.http.get(`${url}?access-token=${this.authtoken}`, {headers});
}