Javascript 为每个 http 请求 Angular 4 显示一个加载 gif

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45323108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:00:23  来源:igfitidea点击:

Show a loading gif for each http request Angular 4

javascripthtmlangulartypescript

提问by mcmwhfy

I'm quite new with Angular so what I need is to show a spinnereach time when a http request is done.

我对 Angular 很陌生,所以我需要的是spinner每次完成 http 请求时都显示一个。

I have many components:

我有很多组件:

<component-one></component-one>
<component-two></component-two>
<component-three></component-three>
<component-n></component-n>

Each one has a http request that get or save some data so when the http request is made I want to show my <loading></loading>component so I suppose is not a good practice injecting my loading component in each other component with a http request. Can I add a filter or something from angular that allows me to load the <loading>component automatically in each component that has an http request?

每个都有一个 http 请求,用于获取或保存一些数据,因此当发出 http 请求时,我想显示我的<loading></loading>组件,所以我认为将我的加载组件注入到具有 http 请求的其他组件中并不是一个好习惯。我可以从 angular 添加过滤器或其他东西,让我<loading>在每个有 http 请求的组件中自动加载组件吗?

Also when the http request is done I want to show a message like "Done" or someting.

此外,当 http 请求完成时,我想显示一条消息,如“完成”或某事。

If anyone can provide me a solution for that I'll really appreciate, ty.

如果有人可以为我提供解决方案,我将非常感激,ty。

回答by Vadim Khamzin

UPD: plunker. Take a look at app.ts. Sorry for having everything in a single file.

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

In Angular 4.3 there is a new HttpClientModule which supports interceptors. The main idea is to have something like this:

在 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;
    }
}

And then you just apply the logic from Christopher's answer to your HttpInterceptor.

然后您只需将 Christopher 的回答中的逻辑应用于您的 HttpInterceptor。

The only thing you should be aware of are simultaneous request. This can be solved for example by generating a unique identifier to each request and storing it somewhere until the request is finished.

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

Then you can have a global LoadingIndicatorcomponent which injects LoadingIndicatorService.

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

For more details on HttpClientModule: https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b

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

回答by Christopher

An http request returns an Observablethat can be subscribed to.

http 请求返回一个Observable可以订阅的。

For example, let's take the authentication of a user.

例如,让我们以用户的身份验证为例。

In my service:

在我的服务中:

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());
}

I call and subscribe to this method in my component:

我在我的组件中调用并订阅了这个方法:

 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
         }

Note the boolean isLoadingthat is set to true before trying to log in our user, and to false once the authentication is succesful.

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

This means that you can show and hide your loading animation with this boolean, like such:

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

<loading-component *ngIf="isLoading"></loading-component>

回答by Alex Klaus

Check out this two npm packages:

查看这两个 npm 包:

  1. ngx-progressbar, which can show a waiting indicator automatically per request (see automagic loading bar), router eventsor whenever you need. See demo.

  2. ng-http-loader(for Angular 4.3+ only), which does the same job in a more traditional way and has fancy spinners from SpinKit.

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

  2. ng-http-loader(仅适用于 Angular 4.3+),它以更传统的方式完成相同的工作,并具有来自SpinKit 的精美旋转器。

回答by Sanjay Singh

With angular 2+, Create a reusable util component

使用 angular 2+,创建一个可重用的 util 组件

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-progress-mask',
  templateUrl: './progress-mask.component.html',
  styleUrls: ['./progress-mask.component.css']
})
export class ProgressMaskComponent implements OnInit {
  @Input() showProgress:boolean = false;
  constructor() { }

  ngOnInit() {
  }

}

The html part:

html部分:

<div class="loadWrapper" *ngIf="showProgress">  
  <div class="loader"></div>  
</div>

the CSS part:

CSS部分:

.loadWrapper {  
    background: rgba(0,0,0,0.3);  
    width: 100%;  
    height: 100%;  
    position: fixed;  
    top:0px;  
    left:0px;  
    z-index: 99999;  
}  
.loader {
    border: 5px solid #f3f3f3; /* Light grey */
    border-top: 5px solid #3d3e3f; /* gray */
    position: absolute;
    left: 50%;
    top: 50%;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

Now insert this to your component

现在将其插入到您的组件中

<app-progress-mask [showProgress]="showMask"></app-progress-mask>

<app-progress-mask [showProgress]="showMask"></app-progress-mask>

Bind showMask of your component to the reusable util component

将组件的 showMask 绑定到可重用的 util 组件

回答by Wesley Coetzee

in your component.ts

在你的 component.ts

public loading: boolean = false;

inside your component.html

在你的 component.html 里面

<div *ngIf="!loading">
  <component-one></component-one>
  <component-two></component-two>
  <component-three></component-three>
  <component-n></component-n>
</div>

<loading *ngIf="loading"></loading>

Whenever you need to see the loading icon, simply set this.loading = true;and to hide it this.loading = false;This will hide the components you do not want to see while loading and display the loading icon instead

每当您需要看到加载图标时,只需设置this.loading = true;并隐藏它this.loading = false;这将隐藏您在加载时不想看到的组件并显示加载图标