I have a LOG IN page and as soon as I fill out the form I get to the home page and on the home page I want to display the username by ID.
For example userName = "Lior"
So on the home page I want it to say Hello Lior
HttpClient:
GetUser(id: string):Observable<User>{
return this.http.get<User>(this.baseUrl this.usersUrl '/' id)
}
Login.ts
login(){
this.usersService.GetAllUsers()
.subscribe(res=> {
const user = res.find((a:any)=>{
return a.userName === this.loginForm.value.userName && a.password === this.loginForm.value.password
});
if(user){
alert("Login Success!");
this.loginForm.reset();
this.router.navigate(['home']);
}
HomePage.ts:
user!: User;
constructor(private usersService: UsersService,private route:ActivatedRoute) {
}
ngOnInit(): void {
// this.accountService.GetUser(this.user.id).subscribe(res => {
// this.user = res;
// })
this.route.paramMap.subscribe(
params =>{
const id = params.get('id');
if(id){
this.usersService.GetUser(id)
.subscribe(
response =>{
this.user = response;
}
)
}
}
)
}
HomePage.html
<div >
<div >
<h1>Hi {{user?.userName}}!</h1>
</div>
</div>
I get that user untifiend
CodePudding user response:
I can not see anywhere that you send the id parameter. you cand send parameters like this:
this.router.navigate(['home'], { queryParams: {id: user.id}});
and use
this.route.queryParamMap.subscribe()
for subscription. Also, subscribe to route in the constructor()
instead of ngOnInit()
.
Besides this, there are some problems with your code and your idea to get the user. first, do not use subscribe inside subscribe. for example, you can use switchMap
here. second, unsubscribe() all your subscriptions to avoid memory/DOM leak.
when you need to keep track of a property (user in this example) in some parts of your application you are facing a term called "state management" you can use a simple service with an rxjs Subject in it or in larger apps using Ngrx or so on.