Reputation: 12179
I have a service that gets a user asynchronously, I need to get the user from the service but only after the user is fetched from the server. Is it possible to get the user from my service and wait until the user is fetched then return it?
Something like this?
Is this something promises can do?
Upvotes: 1
Views: 812
Reputation: 19764
It's possible, as stated in Maximus's answer, but this is not the Angular way to do things. Instead, you should leverage Observables and async
pipe.
Your service should simply return an Observable of users
@Injectable()
export class MyService {
constructor(private http: HttpClient) {}
getUsers = this.http.get(`my.api/users`)
}
Inject this service in your component. If you don't need to do any transformation over data, just use async
pipe in the template.
<ol *ngFor="let user of myService.getUsers | async">
<li>{{ user.name }}
</ol>
From the docs:
The async pipe subscribes to an
Observable
orPromise
and returns the latest value it has emitted. When a new value is emitted, theasync
pipe marks the component to be checked for changes. When the component gets destroyed, theasync
pipe unsubscribes automatically to avoid potential memory leaks.
If you need to transform the data, you can use the map
operator from RxJS.
Upvotes: 1
Reputation: 105497
Yes, you can implement the method like this:
userPromise;
constructor() {
userPromise = http.get();
}
get() {
return userPromise;
}
Upvotes: 1