Z
Z
zlodiak2021-02-21 12:54:43
Angular
zlodiak, 2021-02-21 12:54:43

Why is the spinner not showing up?

I have an application where after the app.component is loaded, an http request is sent. The interceptor intercepts any requests in such a way that before the request, the display state of the spinner is true, after the request is completed, the display state of the spinner is false. The state of the spinner is stored in the service as a BehaviourSubject.

The problem is that the spinner is not displayed at all, although I deliberately added a delay to the request through delay. Please help me understand how to display a pinner while running an http request.

DEMO

Here is the spoiler code:

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(private globalService: GlobalService) {}

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    request = request.clone({
      setHeaders: { Authorization: `Bearer 123` }
    });

    this.globalService.setSpinnerState(true);

    return next
      .handle(request)
      .pipe(finalize(() => this.globalService.setSpinnerState(false)));
  }
}


Request sending service code:
@Injectable({
  providedIn: "root"
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getData() {
    console.log("start request");
    return this.http
      .get("https://jsonplaceholder.typicode.com/todos/1")
      .pipe(delay(2000))
      .subscribe((res: any) => {
        console.log(res);
        console.log("end request");
      });
  }
}


Spinner service code:
@Injectable({
  providedIn: "root"
})
export class GlobalService {
  private isShowSpinner = new BehaviorSubject(false);

  constructor() {}

  spinner() {
    return this.isShowSpinner.asObservable();
  }

  setSpinnerState(state: boolean) {
    return this.isShowSpinner.next(state);
  }
}


Component code:
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  isShowSpinner: boolean;
  constructor(
    private apiService: ApiService,
    private globalService: GlobalService
  ) {
    this.apiService.getData();
    this.globalService.spinner().subscribe((state: boolean) => {
      this.isShowSpinner = state;
    });
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question