I am currently facing an issue with my HTTP provider where I need to access a token value stored in local storage during a GET request. The token value is retrieved using another provider through the getToken function in the HTTP provider. However, I am unable to successfully retrieve the token value in the HTTP call. Can anyone offer guidance on the correct approach to solve this?
Any advice would be greatly appreciated.
this.httpProvider.doGetRequest(Constants.API_SERVER_URL+Constants.API_ENDPOINT_THREADS)
.subscribe(res => {
console.log(res);
this.loading.dismiss();
}, (error) => {
console.log(error);
this.err = error;
this.loading.dismiss();
this.presentToast();
});
HTTP provider class :
@Injectable()
export class HttpProvider {
constructor(public http: HttpClient,
public dataProvider: DataProvider,
public locStor: LocalStorageProvider) {
console.log('Hello HttpProvider Provider');
}
public doGetRequest(url: string) {
return this.http.get(url, this.getHeaders());
}
public doPostRequest(url: string, params: any) {
return this.http.post(url, params);
}
public getHeaders() {
return {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer test',
'token': this.getToken()
},
params: new HttpParams()
};
}
private getToken() {
this.locStor.getValue(Constants.LS_KEY_USER_TOKEN).then((val) => {
return val;
});
}
}
Updated version
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {HttpHeaders} from "@angular/common/http";
import {LocalStorageProvider} from "../local-storage/local-storage";
import {Constants} from "../../app/constants";
import {Headers} from "@angular/http";
import {HttpParams} from "@angular/common/http";
import {DataProvider} from "../data/data";
import 'rxjs/add/observable/fromPromise';
import { Observable } from 'rxjs/Observable';
import {FromObservable} from "rxjs-compat/observable/FromObservable";
import {PromiseObservable} from "rxjs-compat/observable/PromiseObservable";
@Injectable()
export class HttpProvider {
constructor(public http: HttpClient,
public dataProvider: DataProvider,
public locStor: LocalStorageProvider) {
console.log('Hello HttpProvider Provider');
}
public doGetRequest(url: string) {
//return this.http.get(url);
return Observable.fromPromise((this.getHeaders()).flatMap((headers) => {
this.http.get(url, headers);
}));
}
public doPostRequest(url: string, params: any) {
return this.http.post(url, params);
}
public getHeaders() {
return this.locStor.getValue(Constants.LS_KEY_USER_TOKEN).then((val) => {
return {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer test',
'token': val
},
params: new HttpParams()
};
});
}
private getToken() {
this.locStor.getValue(Constants.LS_KEY_USER_TOKEN);
return '222';
}
}