Victor Mendes
Victor Mendes

Reputation: 179

Angular 2 ng-spin-kit

I'm using ng-spin-kit in Angular 2 project.

In the component I have this code:

loading: boolean;

setTimeout(() => { this.loading = true },
  1000
);

and in the html I have this:

<sk-fading-circle class="loader" [hidden]="loading"></sk-fading-circle>

So, I made the spinner runs, but it runs only for 1000ms.

I need the spinner to run until the contents of the API are loaded.

I don't know if setTimeout() is the best way to do this.

Does anyone know how can I do this?

UPDATE

this is the service

export class AppService {

  endPoint = AppConstants;
  handler = AppHandler;

  constructor(private http: Http) {}

  getCandidates() {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

    return this.http.get(this.endPoint.API_ENDPOINT_GET_CANDIDATES, {
      headers: headers
    })
      .toPromise()
      .then((res: Response) => {
        const data = res.json();
        const allCandidate = [];

        data.result.forEach((entry) => {
          const candidate = new Candidate();

          candidate.college = entry.college;
          candidate.cultural_fit = entry.cultural_fit;
          candidate.email = entry.email;
          candidate.graduation = entry.graduation;
          candidate.logic_test = entry.logic_test;
          candidate.mobile_phone = entry.mobile_phone;
          candidate.name = entry.name;

          allCandidate.push(candidate);
        });
        return allCandidate;
      })
      .catch(this.handler.handleError);
  }

}

Upvotes: 0

Views: 314

Answers (3)

crash
crash

Reputation: 4512

This is how I would do it

loading: boolean = false;
getCandidates() {
  // ...

  this.loading = true;

  return this.http.get(this.endPoint.API_ENDPOINT_GET_CANDIDATES, {
    headers: headers
  }).map(res => res.json())
  .catch(this.handler.handleError)
  .finally(() => this.loading = false)
  .subscribe(res => {
    // ...
  });
}

Upvotes: 1

Ludwig
Ludwig

Reputation: 1272

First you should use *ngIf like that:

<sk-fading-circle class="loader" *ngIf="loading"></sk-fading-circle>

In the component use

loading: boolean = true;

If your api uses Observables then your code should look like that:

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

That causes as soon as the data is loaded the spinner gets removed.

Upvotes: 0

Dan R.
Dan R.

Reputation: 648

There are few options possible, The main ones are:

  1. Use an observable to retrieve the data from your API (which is already a part of angular's HTTP), subscribe and set the loading to false after data/error is retrieved
  2. Pass a callback function to be executed when you finish.

Upvotes: 0

Related Questions