Angular 2 service initialization logic

I have angular 2 service called JwtService.ts used to check for JWT token and use it in my different components in order to know if the user is a guest or logged in member.

I get the token fine from my LocalStorage every time the service starts, but for some reasons it’s looking for it 3 times (every time a component using the service) and I’m pretty sure it has to be retrived only once for all components.

Look at the following code of my JwtService.ts:

export class JwtService {

    private jwtToken = localStorage.getItem("jwt");
    public myData = this.getUserData();

    constructor(public router: Router,private http: Http) {
    }

    getToken() {
        return this.jwtToken;
    }

    setToken(theToken)
    {
        localStorage.setItem('jwt', theToken);
        this.jwtToken = localStorage.getItem("jwt");
    }

    logOut()
    {
            this.jwtToken = null;
            localStorage.removeItem("jwt");
            this.router.navigate( ['Home'] );
    }

    getUserData()
    {
    console.log("Getting user..");
    this.http.get('http://localhost/PokemonAPI/public/api/v1/thisUser?token='+this.getToken())
      .map((res:Response) => res.json())
      .subscribe(
        data => {this.myData = data.user;
        console.log()
        },
        err => {
            this.JwtService.checkToken(err);
            console.error(err); },
        () => console.log("User logged!");
      );
    }

    getUser()
    {
        return this.myData;
    }
}

Yes, it works, but if I check my browser console I see this:

Console

which means the browser loaded the service 3 times and used my HTTP GET 3 times in one run.
Why is that and what can cause this?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I assume this is because you added

providers: [JwtService]

on 3 different components.

Add it only on the root component (AppComponent) or alternatively in bootstrap(AppComponent, [JwtService]);

For each component where you add it a new instance is maintained by DI.