Yeonsan
Yeonsan

Reputation: 21

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

Upvotes: 0

Views: 2614

Answers (4)

Amirreza
Amirreza

Reputation: 683

for me it was because of the way i was calling service:

instead of this way:

public CreateFormFile(){}

I should have used this way

public CreateFormFile = () => {}

Upvotes: 0

Reza Rouzbahani
Reza Rouzbahani

Reputation: 63

make sure that you redirect to HomeComponent with standard way of angular ( for example : routerLink ) . if you use Complete route , your page will be Refresh and after that all service are empty .

Upvotes: 3

S.Voulgaris
S.Voulgaris

Reputation: 314

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;
  });
}

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21658

You are most likely providing the service somewhere else. Search for all instances of the LoginService and make sure that you are not providing it in another module or component.

If it appears in the provides array of another module or component you will not have a global singleton instance of the service.

Upvotes: 0

Related Questions