Issue
I'm facing a basic Angular (Javascript) issue. I'm making a call to an API that will give me the list of some roles such as Admin, Viewer, Guest etc. I want to display the same list on the UI.
Things i tried:
TS:
ngOnInit() {
this.roles$ = this.populateRoles();
}
populateRoles(): any {
let role = [];
this._authService.getRoletList().subscribe((res: any) => {
role = res.roles.map((item: any) => {
return item.roleName;
});
console.log('role list', role); // printing correct roles
});
}
HTML:
<li *ngFor="let item of roles$ | async">
{{ item }}
</li>
The list on UI is empty even though console log is printing the correct list. Please point out the mistake.
Solution
The idea of using the async
pipe is for subscribing to an observable reactively. The logic you have on ngOnInit is correct but the problem is populateRoles
does not return an observable, it returns nothing, is void
.
Since you are using async
pipe, you should not subscribe manually in your code, you could make the following changes:
ngOnInit() {
this.roles$ = this.populateRoles();
}
populateRoles(): Observable<yourTypeGoesHere> {
return this._authService.getRoletList().pipe(
map(res => res.roles.map(item => item.roleName)),
tap((data => console.log('items: ', data)))
);
}
Notice how populateRoles
does not subscribe and it returns an observable. If you need to handle some logic from the observable then simply pipe
it and handle whatever it needs to do there.
Answered By - Andres2142
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.