DevBrother
Back to Blog
Web DevelopmentJavaScript
Authentication service or how i spent 3 hours

Several years was coding on react, but now faced with Angular injections.

Yuriy GolikovJune 2, 20202 min read
Authentication service or how i spent 3 hours

Several years was coding on react, but now faced with Angular injections. If you're looking for a software development agency, this guide to building a simple authentication service can help:

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
  public currentUserSubject: Subject<User>;
  public token: string = '';  constructor(private http: HttpClient, private router: Router, private localStorageService: LocalStorageService) {
    this.currentUserSubject = new Subject<User>();
  }  authorization = (token): string => `${TOKEN_TYPE} ${token}`;  setLocalUser = (user: User) => {
    if (user && user.access_token) {
      localStorage.setItem(CURRENT_USER, JSON.stringify(user));
      this.currentUserSubject.next(user);
      this.router.navigate(['/']);
    } else {
      localStorage.removeItem(CURRENT_USER);
      this.currentUserSubject.next(null);
      this.router.navigate(['/login']);
    }
  }  getCurrentUser() {
    return this.http.get<any>(`${environment.apiUrl}/${ROUTES.AUTHENTICATE}`, {
      headers: {
        Authorization: this.authorization(this.token), // TODO USE INTERCEPTORS
      }
    })
      .pipe(
        map((user): any => {
          this.setLocalUser(user);
          return user;
        }),
        catchError(err => {
          this.setLocalUser(null);
          return of(null);
        })
      );
  }
}

Everyting going well until i had to subscribe in component on current user of auth service:

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  providers: [AuthenticationService]
})
export class HeaderComponent implements OnInit {  user: User;
  constructor(private authenticationService: AuthenticationService) {
  }  ngOnInit(): void {
    this.authenticationService.currentUserSubject.subscribe((user) => {
      this.user = user;
    });
  }  logout(): void {
    this.authenticationService.logout();
  }
}

I was getting updates on next only once after i refresh page, but

this.currentUserSubject.next(user); 

in service currentUserSubject was updated, couple hours i was looking for answers on stackoverflow & medium, no success & i called to my friend who have been working for a several years with Angular, he told me that using this

providers: [AuthenticationService]

in decorator creates new instance of service and obviously i was trying to get update from another service instance. So, i just removed this line and everything starts to work perfect.

Stay Updated

Get the latest insights on AI, MLOps, and engineering delivered to your inbox.