Issue
I am having difficulty grasping some of the concepts. Such as I have created a subscription to my SQL DB (users) upon login and I am able to present the data on the page (DOM). However, I a now trying to pull out specific data from the item to save for later use in my typescript file.
login.component.ts
this.usersService.getUsers()
.subscribe((result: users) => (this.users[0] = result));
users.service.ts
public getUsers() : Observable<users> {
let userEmail = sessionStorage.getItem('userEmail');
return this.http.get<users>(`${environment.apiUrl}/${this.url}/${userEmail}`);
login.component.html
<div class="row" style="background-color:transparent;">
<mat-card *ngFor="let user of user" class="ecard">
<mat-card-title>{{user.role}}</mat-card-title>
</mat-card>
</div>
This works as expected.
However, I would like to use information from the 'user' to perform other functions in the ts file.
The below actions are returning undefined values
console.log(this.users);
console.log(this.users.values);
And this action returns an error of "can not read 'fname'
sessionStorage.setItem('userDisplayName', this.users[0].fname);
Solution
An observable is asynchronous. So you only can be sure you get the value inside "subscribe function" (well, in subscribe function you can call to another function passing as argument the response)
**WRONG**
this.usersService.getUsers()
.subscribe((result: users) => (this.users[0] = result));
sessionStorage.setItem('userDisplayName', this.users[0].fname); //<--this is outside
// subscribe function
**OK**
this.usersService.getUsers()
.subscribe((result: users) => {
this.users[0] = result;
sessionStorage.setItem('userDisplayName', this.users[0].fname);
})
**OR OK Too**
this.usersService.getUsers()
.subscribe((result: users) => {
this.users[0] = result;
doSomething(this.users[0])
})
doSomething(user:any)
{
sessionStorage.setItem('userDisplayName', this.users[0].fname);
}
NOTE: To log or store the result, it's common use the rxjs operator "tap" in the observable. This operator makes that, when someone subscribe it's executed the function
public getUsers() : Observable<users> {
let userEmail = sessionStorage.getItem('userEmail');
return this.http.get<users>(`${environment.apiUrl}/${this.url}/${userEmail}`).pipe(
tap((res:any)=>{
sessionStorage.setItem('userDisplayName', res.fname);
})
)
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.