rochana
rochana

Reputation: 5

How to access a username in an entire application developed using angular?

I am currently working on an Application using Angular, Express and MySQL. I want to extract a username from the database and pass it to the front end and access it throughout the application user-area when the user login function is executed correctly. I am somewhat aware that i can use a service.ts file to do this, but i don't know exactly how to. Can i have some help?

Upvotes: 0

Views: 1236

Answers (2)

Gabriel Luca
Gabriel Luca

Reputation: 215

  1. Crate an AuthService.ts as you said
  2. inside your service define an observable (can be BehaviourSubject)of user info type
  3. in your api service where you get the user info inject the AuthService use next on the defined observable to update all subscribers (or method call defined in service) with received data
  4. inject the service in the components you need the user info / profile
  5. in components subscribe to that observable
interface UserInfo {
  email: string;
  dob: string;
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  UserInfo: BehaviorSubject<UserInfo> = new BehaviorSubject(null);

  updateUserInfo(data: UserInfo) {
    this.UserInfo.next(data);
  }

}

In api service where you get the user info you call updateInfo with the received data (you have to add the auth service to api service constructor with an access modifier private, protected, public to have it injected by angular)

In component:

export class HeaderComponent implements OnInit {
  u: UserInfo;

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authService.UserInfo.subscribe(x=>this.u=x)
  }

}

Now you can bind to the "u" field in the component.

Using an observable will help you update all listeners / subscribers (all places where it's used).

Upvotes: 1

Eliseo
Eliseo

Reputation: 57971

the good of services is that live along of the life of the application. As a service is only a class, you can has a service with a variable where you store the value

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {

  userName;
  constructor(httpClient:HttpClient) { }

  getUserName(user:string,password:String)
  {
      this.post('...your..api...',{user:user,password:password).pipe(tap(
           res=>{
               if (res==true)
                   this.userName=userName
           }
      ))
  }

}

Where I suppouse you has an url that receive as post {username:...,password:...} and return true if is logged or false if not

All component that inject this service, can use and change the variable "userName". If you want to see in the .html , in the constructor declare the variable as public

constructor(public dataService:DataService){}

//and in the .html
{{dataService.userName}}

Upvotes: 0

Related Questions