Reputation: 5
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
Reputation: 215
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
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