1

I have a service in my Angular App which is used to retrive some data from my API.

I would be able to show a spinner to the user while that data is being fetched.

How should i archieve it?

My service looks like this:

export class MenuComponibileService {
  constructor(private http: HttpClient, private adapter: MenuComponibileAdapter) { }

  getMenuComponibile(idNegozio: string, piva: string, lang: string, type: string, idPlu: number): Observable<MenuComponibile[]>{
    return this.http
    .get(`${Globals.API_URL}/mc/${piva}/${idNegozio}/${idPlu}`, {params: { lang, type }})
    .pipe(map((data: any[]) => data.map(item => this.adapter.adapt(item))));
  }
}

And i get the data like:

  ngOnInit(): void {
    this.menuComponibileService
    .getMenuComponibile(this.idNegozio.toString(), this.piva, 'IT', this.tipo, this.plu.id)
    .subscribe((data) => {
      this.menuComponibile = data;
    });
  }

I was going to add like a variable loading = true and i was going to set it inside the subscribe like this:

  loading = true;
  ngOnInit(): void {
    this.menuComponibileService
    .getMenuComponibile(this.idNegozio.toString(), this.piva, 'IT', this.tipo, this.plu.id)
    .subscribe((data) => {
      this.menuComponibile = data;
      this.loading = false;
    });
  }

when based on loading value i was going to show or not the spinner, but how should it be done correctly?

1 Answer 1

1

As you've pointed out, you can do it that way, or if you want something more RXJS related, you can use defer & finalize

You can create a function that handles the observable like

 get GetMenuComponibile(): Observable<any>{
    return defer(() => {
      this.loading = true;
      return this.menuComponibileService
     .getMenuComponibile(this.idNegozio.toString(), this.piva, 'IT', this.tipo, this.plu.id)
     .finalize(() => this.loading = false)
    });
  }

Then you can call it like

  this.GetMenuComponibile.subscribe((data) => {
    this.menuComponibile = data;
    this.loading = false;
  });

However, it's a syntactically more complex version of what you've already proposed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.