首页 > 解决方案 > Angular 8微调器或加载器使用不相关的组件

问题描述

这是我在StaffMembers.ts组件下面的代码。

import { Component, OnInit } from '@angular/core';
import { StaffService } from '../_services/Staff.service';
import { Router, NavigationExtras } from "@angular/router";

@Component({
  selector: 'StaffMembers',
  templateUrl: './StaffMembers.html'
})

export class StaffMembers implements OnInit {
  public StaffArr: Array<any>;
  constructor(private _StaffService: StaffService, private _router: Router) {
  }

  async ngOnInit() {
    this.StaffArr = await this._StaffService.GetStaff();
  }
}

下面是我的Staff.service.ts服务组件。

import { Injectable, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { HostedPathConst } from '../_helpers/path';

@Injectable({
  providedIn: 'root'
})
export class StaffService {
  private messageStaffSource: BehaviorSubject<Staff>;
  public currentStaffMessage: Observable<Staff>;
  private _Staff: Staff;
  private ProfileFile: FileList;
  private sL: Array<Staff> = new Array();


  constructor(private http: HttpClient, private toastr: ToastrService) {
    this.messageStaffSource = new BehaviorSubject<Staff>(new Staff());
    this.currentStaffMessage = this.messageStaffSource.asObservable();
  }

  GetStaff(): Promise<any> {
    const promise = this.http.get(HostedPathConst.HostedPath + `Staff/GetStaff`).toPromise();
    return promise;
  }

  Error(data) {
  }
  Success(data) {
    this.toastr.success(data.errorMessage, 'Success !');
  }
}

现在,当我想在页面上添加我的加载器时,我从这个 URL 中找到了一个按预期工作的包。
https://www.npmjs.com/package/@tusharghoshbd/ngx-loader

当我在任何 HTML 页面中使用它时,它就是通过这种方式调用的。

<ngx-loader [show]="show" [fullScreen] = "fullScreen" [template]="template"> Loading... </ngx-loader>

并且在任何组件文件中都以这种方式调用。

  //Declaration
  show = false;
  fullScreen = true;
  template = ``
   //Initialization
  this.show = true;
  this.fullScreen = true;
  this.template = ``;
  //And to stop the loader
  this.show = false

现在就像我在上面为 html 组件服务two unrelated components Staff.service.ts提供的StaffMembers.ts一样,因为我想在从

async ngOnInit() {
    this.StaffArr = await this._StaffService.GetStaff();
  }

我如何等待我的数据被加载以启动和停止加载器或微调器

标签: angulartypescriptangular8

解决方案


如果你想让它们分开(你应该),我会使用 http 拦截器。

媒体上有一个很好的例子:https ://medium.com/swlh/angular-loading-spinner-using-http-interceptor-63c1bb76517b

检查代码:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import {catchError, map} from 'rxjs/operators'
import {LoadingService} from '../../layout/services/loading/loading.service';

/**
 * This class is for intercepting http requests. When a request starts, we set the loadingSub property
 * in the LoadingService to true. Once the request completes and we have a response, set the loadingSub
 * property to false. If an error occurs while servicing the request, set the loadingSub property to false.
 * @class {HttpRequestInterceptor}
 */
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {

  constructor(
    private _loading: LoadingService
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this._loading.setLoading(true, request.url);
    return next.handle(request)
      .pipe(catchError((err) => {
        this._loading.setLoading(false, request.url);
        return err;
      }))
      .pipe(map<HttpEvent<any>, any>((evt: HttpEvent<any>) => {
        if (evt instanceof HttpResponse) {
          this._loading.setLoading(false, request.url);
        }
        return evt;
      }));
  }
}

在此示例中,作者使用服务来共享状态更改。你也可以使用事件,但它会更棘手,因为它超出了 angular 的运行范围


推荐阅读