James, it would be beneficial for your service to return observables that you can subscribe to in the component. If you need to manipulate the response in the service, consider using "tap". For example:
NOTE: The purpose of using map is to transform the response. If no transformation is needed, do not use it.
ListAllUsers() {
// Ensure that you use "return"
return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(tap(response => {
..work with the response here..
..similar to what you have in the subscribe method...
}
In your component:
// Make sure to assign this.Userlst within the subscribe function
this.UserService.ListAllUsers().subscribe(_=>{
this.Userlst=JSON.parse(sessionStorage.getItem('userlist'));
}
NOTE: If you don't want the value to persist between sessions, storing it in SessionStorage may not be necessary.
Update regarding storage in SessionStorage. If we want the service to return data like userarray
, we should utilize "map" to transform the data.
ListAllUsers(): Observable<any>{
// Indicating that an Observable will be returned
return this.http.get<any>(`${environment.apiUrl}GetAllEndUsers`, { headers: this.header })
.pipe(
.map((result: any) => {
// The mapping process can be as complex as required
this.userList.push(result);
this.userData = this.userList[0].response;
var status: any;
const userarray:any=[];
for (let i = 0; i < this.userData.length; i++) {
// Using a ternary operator instead of if statements
const status=(this.userData[i].status == "True")?"Active":"Inactive";
this.userkeypair = {
"id": this.userData[i].id, "name": this.userData[i].fullName, "email": this.userData[i].emailId, "account": this.userData[i].relatedAccount,
"status": status
}
userarray.push(this.userkeypair);
}
// Simply returning the transformed value
return userarray;
});
}
In our component:
this.UserService.ListAllUsers().subscribe(response=>{
this.Userlst=response
}