I have an Angular 13 application and I have a UserRole service that I have used in many pages.
But I cannot get the value of this object. I call the services in the main component but when I get the results i have undefined.
@Injectable({
providedIn: 'root'
})
export class UserRoleService {
_userRole!: UserRole;
get userRole(): UserRole {
if (!this._userRole) {
this.getUserRole();
}
return this._userRole;
}
getUserRole(): any {
this._httpClient.get<UserRole>(this.requestUrlBase "/role", { headers: this.h }).subscribe({
next: (res: UserRole) => {
this._userRole = res;
},
});
}
@Component({
selector: 'app-root',
providers: [UserRoleService],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
...
role!: UserRole;
constructor(userRoleService: UserRoleService, ...,) {
}
ngOnInit(): void {
this.userRoleService.getUserRole();
...
this.role = this.userRoleService.userRole;
}
CodePudding user response:
this function getUserRole()
is async function - it's sending HTTP request, so ofcourse it will not filled the variable when you return it - return this._userRole;
I suggest storing the Observable
in the service as is:
_userRole: Observable<UserRoll> = this._httpClient.get<UserRole>(this.requestUrlBase "/role", { headers: this.h })
and subscribe
to the value inside the component
if you want to make only one request to the server you can do it that way: in the service:
getUserRole(): any {
if (!!this._userRole) {
return of(this._userRole)
}
return this._httpClient.get<UserRole>(this.requestUrlBase "/role", {
headers: this.h }).pipe(
tap(user => this._userRole = user)
)
this way you'll make an HTTP request only if there's no user
CodePudding user response:
Change your getUserRole
method to return a promise instead something like
import { lastValueFrom } from 'rxjs';
export class UserRoleService {
_userRole!: UserRole;
async getUserRole(): Promise<UserRole> {
if(!!this._userRole){
return Promise.resolve(this._userRole);
}
let userRole= this._httpClient.get<UserRole>(this.requestUrlBase "/role", { headers: this.h });
this._userRole=await lastValueFrom(userRole);
return Promise.resolve(this._userRole);
}
}
then and await for the promise to resole in your component
this.userRoleService.getUserRole().then((role)=>{
this.role=role;
})
if you are not using the latest version of rxjs and lastValueFrom is not available then use toPromise instead
let userRole= this._httpClient.get<UserRole>(this.requestUrlBase "/role", { headers: this.h }).toPromise();
this._userRole=await userRole;