I am using Angular 9.0.7 on my current project. I have a backend written in Node.js (Express) with a frontend written in Angular.
The issue I encounter is that my service is not calling the function that handles the request to the backend to retrieve data on the first load, it does however work if I refresh the page.
I have a deviceService.ts file where I handle all the requests related to the devices. I have a Get Request to retrieve all the devices I have in the database. The authentication token is being loaded and I can see it, the device request is not going through on the initial load. The function of the deviceService.ts file looks like this:
getAllDevices(){
this.authenticationService.login(this.username, this.password);
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'auth-token': localStorage.getItem('auth-token')
});
const options = { headers };
return this.http.get(`${environment.apiUrl}/pm/devices?pa_id=${this.pm_id}`, options);
}
What I am then doing, is adding the devices I receive from this request to a localStorage called devices in the component that I am using it for. This component appears on the home page on the initial load. The function looks like this:
ngOnInit(): void {
this.deviceService.getAllDevices().subscribe(data => {
let temp_devices = [];
data['devices'].forEach(device => {
device.supported_memory.forEach(memory => {
var o = Object.assign({}, device);
var model_manufacturer = device.manufacturer + " " + device.model + " " + memory;
var phone_image = device.manufacturer + " " + device.model;
phone_image = phone_image.replace(/\s/g, '');
o.phone_image = phone_image.toLowerCase();
o.model_manufacturer = model_manufacturer;
o.memory = memory;
temp_devices.push(o);
});
});
this.devices = temp_devices;
this.devices = temp_devices.map(function(el, i, array){
var o = Object.assign({}, el);
return o;
});
localStorage.setItem('devices', JSON.stringify(this.devices));
});
}
As mentioned above, I don't understand why the request is not being called on the initial load, but gets called on the second.
This is because this.authenticationService.login(this.username, this.password);
is asynchronous. So first time loading the page when you call getAllDevices the token is not available. You can confirm it by inpecting devTools console.
getAllDevices(){
this.authenticationService.login(this.username, this.password);
// rest code will continue to execute but token will be null
}
Second time loading page, you dont see the problem because token already exist on local storage.
Solution: you should call getAllDevices when token is already available.