angularangular-materialangular-ui-router

Unable to get values from Service in Angular


I have created and application with Login Functionality and want to get the logged In user name in the components

Service File:

  login({ username, password }: any): Observable<any> {
if (username === 'admin@gmail.com' && password === 'admin123') {
  this.setToken('abcdefghijklmnopqrstuvwxyz');
  **this.username1 = username;**
  this.setUserName(username);
  return of({ name: 'Papun Sahoo', email: 'admin@gmail.com' });
}
return throwError(new Error('Failed to login'));

}

On the Component I am trying to access the value

userName?:string;
  constructor(private observer: BreakpointObserver, private router: Router,private loginService: LoginService) {
    **this.userName = this.loginService.getUserName()!;**
    console.log("From Component :"+this.loginService.username1);
  }

but i am getting Undefined here

From Component :undefined

StackBlitz Link to Reproduce

Any help would be appreciated


Solution

  • You are providing LoginService twice, once in root via the @Injectable decorator on the service class, and again in AdminModule in the providers array. Removing the LoginService from the providers in AdminModule resolves the issue.

    Tip: You can guard against multiple instances of services by injecting the service into itself:

    export class LoginService {
      constructor(
        ...
        @Optional() @SkipSelf() private parentLoginService?: LoginService,
      ) {
        if (parentLoginService) {
          throw new Error('Multiple instances of LoginService created!');
        }
      }
      ...
    }
    

    EDIT: To fix page reloading for seemingly no reason, add type="button" to line 22 of your login component:

    <button mat-button class="back" type="button" (click)="login()">Login</button>
    

    The type attribute of <button> tags defaults to "submit", which can cause the page to reload. To avoid this issue in the future, I recommend using the ESLint rule button-has-type.