angulartypescript

Angular 7: Singleton service not working after routing


I have two urls /login and /home. When I log in I want to store the username in a field of the LoginService. This is done on the /login page. Now when I go to /home it's like the service gets created again and all the fields are empty.

This is my service

@Injectable({
    providedIn: "root"
})
export class LoginService {

    public CURRENT_USER: User;
}

this is how I get the service in my components

export class HomeComponent {
  constructor(private loginService: LoginService) {}
}

and here's is my routing module:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import SignUpComponent from './components/sign-up/signup.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'signup', component: SignUpComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now am I missing something or am I doing my routing wrong?

Thanks in advance


Solution

  • If I correctly understand what you want to do, I suggest you to :

    1. Store CURRENT_USER on the local storage and retrieve him whenever you want (user = JSON.parse(localStorage.getItem(CURRENT_USER));)
    2. Set CURRENT_USER as Observable and subscribe() to it on the component/s you want

    There is nothing to do with your routing implementation.It is how Angular life-cycle works.

    UPDATE For the 2nd option : Create a new Service (UserService)

    import { Injectable } from '@angular/core';
    import { Observable, Subject } from 'rxjs';
    
    @Injectable({ providedIn: 'root' })
    export class Userservice {
        private subject = new Subject<User>();
    
        sendUser(currentUser: User) {
            this.subject.next(currentUser);
        }
    
    
        getCurrentUser(): Observable<User> {
            return this.subject.asObservable();
        }
    }
    

    When you login :

    constructor(private userService: UserService) {}
    login() {
      this.userService.sendUser(CURRENT_USER);
    }
    

    On the component you want to get the current user :

    user: User;
    constructor(private userService: UserService) {
      this.userService.getCurrentUser().subscribe(currentUser => {
        this.user = currentUser;
      });
    }