显示每个http请求Angular 4的加载gif

mcm*_*hfy 9 html javascript typescript angular

我对Angular很新,所以我需要的是spinner每次http请求完成时显示.

我有很多组件:

<component-one></component-one>
<component-two></component-two>
<component-three></component-three>
<component-n></component-n>
Run Code Online (Sandbox Code Playgroud)

每个人都有一个获取或保存一些数据的http请求,所以当我发出http请求时,我想显示我的<loading></loading>组件,所以我认为用一个http请求将我的加载组件注入到每个其他组件中是不好的做法.我可以添加一个过滤器或角度的东西,允许我<loading>在每个有http请求的组件中自动加载组件吗?

此外,当http请求完成时,我想显示"完成"或某些消息.

如果有人能为我提供解决方案,我将非常感激,ty.

Vad*_*zin 14

UPD:plunker.看看app.ts.抱歉将所有内容都放在一个文件中.

在Angular 4.3中,有一个新的HttpClientModule支持拦截器.主要的想法是这样的事情:

@Injectable()
export class LoadingIndicatorService {

    private _loading: boolean = false;

    get loading(): boolean {
        return this._loading;
    }

    onRequestStarted(): void {
        this._loading = true;
    }

    onRequestFinished(): void {
        this._loading = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你只需将Christopher的答案中的逻辑应用到你的HttpInterceptor中.

您唯一应该注意的是同时请求.这可以通过例如为每个请求生成唯一标识符并将其存储在某处直到请求完成来解决.

然后你可以有一个LoadingIndicator注入的全局组件LoadingIndicatorService.

有关HttpClientModule的更多详细信息:https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b


Chr*_*her 6

http请求返回Observable可以订阅的请求.

例如,让我们对用户进行身份验证.

在我的服务中:

login(email: string, password: string): Observable<User> {
    let url = this.authUrl + '/login';

    return this.http
        .post(url, JSON.stringify({ email, password }))
        .map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)

我在我的组件中调用并订阅此方法:

 this.isLoading = true;
 this.authService.login(email, password)
        .subscribe(data => {
            this.isLoading = false;
            // Do whatever you want once the user is logged in
            // Where 'data' is the User returned by our http request
         }, error => {
            // Handle errors here
         }
Run Code Online (Sandbox Code Playgroud)

请注意isLoading在尝试登录我们的用户之前设置为true 的布尔值,并且在身份验证成功后设置为false.

这意味着您可以使用此布尔值显示和隐藏加载动画,如下所示:

<loading-component *ngIf="isLoading"></loading-component>
Run Code Online (Sandbox Code Playgroud)


Ale*_*aus 6

查看以下两个npm软件包:

  1. ngx-progressbar,它可以根据请求(请参阅automagic loading bar),路由器事件或您需要的任何时间自动显示等待指示器。参见演示

  2. ng-http-loader(仅适用于Angular 4.3+),它以更传统的方式完成相同的工作,并且拥有SpinKit的花式微调器。