Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

How can i show ngx-spinner until my whole data is loaded in Angular

I have on every page header - image and text. Somoetimes the images are loading slow, the text is showed and after 1-2 seconds the heeader image shows up where it should which is not good user experience. How can i show my ngx-spinner until whole data in my component - loaded as route is comleted?

what i tried - app.component.ts

import { Component } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';

import {
  Router,
  // import as RouterEvent to avoid confusion with the DOM Event
  Event as RouterEvent,
  NavigationStart,
  NavigationEnd,
  NavigationCancel,
  NavigationError
} from '@angular/router'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-app';

  loading = true;

  constructor(private spinner: NgxSpinnerService, private router: Router) {
    this.router.events.subscribe((e: RouterEvent) => {
      this.navigationInterceptor(e);
    })
  }

  ngOnInit() {

  }

  navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      this.loading = true;
      this.spinner.show();
      console.log(1111);
    }
    if (event instanceof NavigationEnd) {
      this.loading = false;
      this.spinner.hide();
    }
    // Set loading state to false in both of the below events to hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this.loading = false;
      this.spinner.hide();
    }
    if (event instanceof NavigationError) {
      this.loading = false;
      this.spinner.hide();
    }
  }


}

app component html

<ngx-spinner bdColor="rgba(51,51,51,0.8)" size="medium" color="#fff" type="ball-scale-multiple">
  <p style="font-size: 20px; color: white">Loading...</p>
</ngx-spinner>

but it is not working. I don't get the spinenr while my routes are chaning and while the compoenent is rendered there

question from:https://stackoverflow.com/questions/65893005/how-can-i-show-ngx-spinner-until-my-whole-data-is-loaded-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using lifecycle hooks for this. with the use of router events we can't define component is fully loaded or not. for this situation you can ngAfterViewInit life cycle.

Check the following site as reference

https://angular.io/guide/lifecycle-hooks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...