el_pup_le
el_pup_le

Reputation: 12179

Waiting for a promise to complete in service

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?

  1. Service constructor begins fetching user from server.
  2. A component that has this service injected needs user from the service and does get()
  3. Service is still fetching the user from the server so at this point the get() need to be delayed.. somehow.
  4. Service finishes fetching user, get() returns user.

Is this something promises can do?

Upvotes: 1

Views: 812

Answers (2)

Lazar Ljubenović
Lazar Ljubenović

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 or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async 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

Max Koretskyi
Max Koretskyi

Reputation: 105497

Yes, you can implement the method like this:

userPromise;
constructor() {
     userPromise = http.get();
}

get() {
     return userPromise;
}

Upvotes: 1

Related Questions