Why data on service isn't saved when changing routes?

Viewed 423

I'm new to angular and i try to build a small app. I have this service who holds a variable and a function:

data.service.ts

data = [];
getData() {
  this.http.get(url).subscribe((res)=>
  this.data.push(res));
};

I also have two routes:

app.module.ts (the service is defined here)

import { DataService } from './data.service';
// ...
const appRoutes = [
  { path: 'home', component: HomeComponent },
  { path: 'settings', component: SettingsComponent }
]
    
@NgModule({
  // ..
  providers: [DataService],
  // ..
})

When i use the getData function in the homeComponent it works fine, and the response is added to the data array. But- and here is the problem- once I navigate to the second route, the data in the service is back to be an empty array.

I would have think that the service is not being "restarted" when i navigate.

So, what is the problem? Thank you.

2 Answers

Problem Found and solved, from a different direction.

I used <a href="/"> as the link to the routes, which probably causes the application to restart itself every time its clicked. <a routerlink="/"> solves the problem.

when you move to a different route, all the local data would be deleted and will be initialized with default values. So , if you want to sustain the data for use in some other page, you will have to save the values inside a globally declared variable.

For declaring global variables, that can be used in all the pages, firstly create a global.service.ts file and import the file into all the components. Wherever you need you can access these global variables as this.global.variableName.

Follow this link on how to create global services.

Change your codes like

after creating global service, import this global service in your app.module.ts, then in home.component.ts import it like

import { GlobalService } from '../global.service';
.
.
.constructor(public global: GlobalService) { }
.
.
getData(){
    this.http.get(url).subscribe((res)=>
    this.global.globalData.push(res);
};
Related