Henry Laney
Henry Laney

Reputation: 33

Angular 7 service not acting as a singleton

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).

Upvotes: 3

Views: 1703

Answers (1)

k.s.
k.s.

Reputation: 3004

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

Upvotes: 2

Related Questions