I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined.
code
export class DashboardService {
public token: any;
constructor(
private env: EnvService,
private http: HttpClient,
private storage: NativeStorage
) {
this.storage.getItem('token').then((token) => {
this.token = token.access_token;
console.log('storage token ', token.access_token);
}).catch(error => console.error(error));
}
getDashboard() {
const headers = new HttpHeaders({
Accept: 'application/json, text/plain',
'Content-Type': 'application/json',
Authorization: this.token
});
console.log('my token ', this.token);
console.log('my headers ', headers);
return this.http.get(this.env.Dashboard + '/dashboard', {headers})
.pipe(
tap(data => {
console.log(data);
})
);
}
}
Screenshot
https://i.stack.imgur.com/hSRN6.png
Another problem I encountered is that my request header only sends 2 values instead of 3 (not sure if it's due to the token being undefined or not).
https://i.stack.imgur.com/YVRNf.png
It should be sending Accept
,Content-Type
,Authorization
but it only sends Accept
and Content-Type
.
Any suggestions?
Update
This is the component where I am utilizing the service mentioned above:
export class DashboardPage implements OnInit {
schools: any = [];
constructor(
private authService: AuthenticationService,
private menu: MenuController,
private dashboardService: DashboardService
) {
this.getSchool();
}
ngOnInit() {
this.menu.enable(true);
}
logout() {
this.authService.logout();
}
getSchool() {
this.dashboardService.getDashboard().subscribe((res) => {
this.schools = res;
});
}
}