显示微调框,直到API响应成角度6

时间:2018-09-16 16:50:11

标签: angular angular6

我是Angular 6的新手,以前没有任何版本的Angular经验,也不使用Angular 6创建我的网站,在该网站中,我必须显示Spinner直到API Response待处理。我正在使用 httpclient 角度6以调用API。我想为每个API请求显示微调框。我搜索了SO,但没有找到问题的答案。下面是我的组件和服务文件。

/* data.services.ts */

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class DataService {
  constructor(private http: HttpClient) { }
  getUsers() {
    return this.http.get('https://jsonplaceholder.typicode.com/users')
  } 
}

/* users.component.ts *

import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
 })

export class UsersComponent implements OnInit {
  users$: Object;
  constructor(private data: DataService) { }
  ngOnInit() {
    this.data.getUsers().subscribe(data => {
      this.users$ = data; 
    });
  }
}

注意:我不想为此使用任何软件包或模块。

有人可以帮我解决这个问题吗?任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:4)

如果您坚持不安装任何软件包,请使用布尔值标志来指示加载是否已完成

https://loading.io/获取加载动画,以将其放入html的加载部分

/* data.services.ts */

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class DataService {
  constructor(private http: HttpClient) { }
  getUsers() {
    return this.http.get('https://jsonplaceholder.typicode.com/users')
  } 
}

/* users.component.ts *

import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
 })

export class UsersComponent implements OnInit {
  users: Object; // <-- Do not use $ at the end of a variable unless it is an observable
  loading = true;
  constructor(private data: DataService) { }
  ngOnInit() {

    this.data.getUsers().subscribe(data => {
      this.users = data;
      this.loading = false;
    });
  }
}

<div *ngIf="loading else loaded">
    loading ...
</div>

<ng-template #loaded>
    <div *ngFor="let user of users">{{user.name}}</div>
</ng-template>

答案 1 :(得分:1)

您可以使用ng4-loading-spinner

执行npm i ng4-loading-spinner --save

将模块导入您的应用程序根模块

import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';

输入一个条目

 imports: [ Ng4LoadingSpinnerModule.forRoot() ]

将微调器组件包括到根级别组件中。

<ng4-loading-spinner> </ng4-loading-spinner>

show()回调中使用hide()subscribe

   import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';
     constructor(
            private spinnerService: Ng4LoadingSpinnerService,
            private data: DataService
        ) { }
       ngOnInit() {
         this.spinnerService.show();//show the spinner
    this.data.getUsers().subscribe(data => {
      this.users$ = data; 
       this.spinnerService.hide();//hide the spinner if success
    },
    (error)=>this.spinnerService.hide();//hide the spinner in case of error
 );
  }}

Live Demo

答案 2 :(得分:1)

为此,我将使用http拦截器来检查http请求期间的某些事件。 让我们拥有将具有一些加载器的组件,并将该组件放置在与路由器插座或应用程序组件相同的级别。 无论是否显示加载程序,我们都会通过拦截器与服务进行通信,以告知我们的组件。

有一个简单的角度6示例: https://stackblitz.com/edit/angular-hgxcsu

答案 3 :(得分:0)

看看我的软件包ngx-RxCache。处理负载是关键用例之一。安装ngx-rxcache。不要在TypeScript中订阅可观察对象,请在视图中使用异步管道。在https://stackblitz.com/edit/angular-3yqpfe

上查看演示

https://loading.io/获取加载动画,以将其放入html的加载部分

/* data.services.ts */

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RxCacheService } from 'ngx-rxcache';
import { User } from 'path to user interface definition';

@Injectable({
  providedIn: 'root'
})

export class DataService {
  constructor(private http: HttpClient, private cache: RxCacheService) { }
  load() {
    this.usersCacheItem.load();
  }

  private usersCacheItem = this.cache.get<User[]>({
      id: '[User] users',
      construct: () => this.http.get<User[]>('https://jsonplaceholder.typicode.com/users')
    });

    users$ = this.usersCacheItem.value$;
    loading$ = this.usersCacheItem.loading$;
}

/* users.component.ts *

import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
 })

export class UsersComponent implements OnInit {
  users$: this.data.users$;
  loading$: this.data.loading$;
  constructor(private data: DataService) {
    data.load();
  }
}
<div *ngIf="loading$ | async; else loaded">
    loading ...
</div>

<ng-template #loaded>
    <div *ngFor="let user of users$ | async">{{item}}</div>
</ng-template>

答案 4 :(得分:0)

您可以将引用作为用户组件属性存储在订阅上,然后在模板中使用简单的* ngIf来显示/隐藏加载指示符:

/* users.component.ts *

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  users$: Object;
  subscription: Subscription

  constructor(private data: DataService) { }

  ngOnInit() {
    this.subscription = this.data.getUsers().subscribe(data => {
      this.users$ = data; 
    });
  }
}

在您的模板中:

...
<div *ngIf="!subscription?.closed">loading...</div>
...

有关订阅类的更多信息,请参见http://reactivex.io/rxjs/class/es6/Subscription.js~Subscription.html

这超出了此问题的范围,但是您还应该在销毁组件时检查订阅是否已关闭(因此在订阅上保留引用可以有所帮助):例如,如有必要,请在ngOnDestroy()中调用subscription.unsubscribe(),或为此目的而从基类扩展(以便您的所有组件都可以从中受益)。

请参见https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/https://netbasal.com/automagically-unsubscribe-in-angular-4487e9853a88