3

I used ng generate to create a service. I initialize an array and change a flag, but when I route to a different page the array is empty and the flag is false.

My service starts with

@Injectable({ providedIn: 'root' })

I understood that would create a application-wide singleton service, but I've only used services on single page applications before now. Is it different with multi-page applications/routing?

edit: I've tried the field's as static which did not work either.

edit 2: This is more or less my problem: angular-7bp9kn.stackblitz.io Initialize on the home page, and display (true). Navigate to admin (after it's been initialized on home) and display (false).

  • 4
    If it's a completely different page (not a different route of a SPA) your value won't be saved since the application is destroyed. – Frank Modica Dec 12 '18 at 20:20
  • Ah, yes it seems to be a different page. Do I use pound signs to do routing for an SPA? – Henry Laney Dec 12 '18 at 20:27
  • 1
    You should use @angular/router module to achieve routing in Angular. – ptesser Dec 12 '18 at 20:29
  • I was, this is what I have in my app routing module: `const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'submit', component: SubmitComponent }, { path: 'admin', component: AdminComponent }, { path: 'calendar', component: CalendarComponent }, { path: 'edit', component: EditComponent } ];` – Henry Laney Dec 12 '18 at 20:45
  • Post a complete minimal example reproducing the problem, in a stackblitz. – JB Nizet Dec 12 '18 at 20:50
  • Good idea, this is more or less my problem: https://angular-7bp9kn.stackblitz.io/home Initialize on the home page, and display (true). Navigate to admin (after it's been initialized on home) and display (false). – Henry Laney Dec 12 '18 at 21:19

1 Answers1

2

I believe ( from your stackblitz example above) your problem is the fact that you're using href instead of routerLink="/home" directive. And since href will do a complete reload of your page with a new uri, seems legit that the service will be reinitialized since the whole app is being bootstraped from scratch.

So bottom line, if you just replace href to routerLink there will be only one instance of your service through the app.

You can read more about it here angular docs

k.s.
  • 2,964
  • 1
  • 25
  • 27