Angular 13 如何在渲染组件之前加载数据?

473 阅读1分钟

本教程讲述了如何在渲染组件前加载数据。

这篇文章包括在组件渲染前从API加载数据。

我们有多种方法可以在组件渲染前加载API数据:

  • 一种方法是在构造函数中调用API和承诺
  • 第二种方式,使用解析数据
  • 最后,激活路由

在这篇文章中,我们要讨论的是第一种方法

如何在渲染组件之前加载API数据

让我们创建一个Angular服务,从API或数据库中获取数据。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private employee_api_url: string = 'api.localhost.com';

  constructor(private httpClient: HttpClient) { }


  getEmployees(): Observable<any> {
    return this.httpClient.get(this.employee_api_url + '/read')
      .pipe(map((resp: any) => resp.json()),
        catchError(error => this.throwError(error))
      )

  }


  throwError(error: any) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

在Angular组件中,为构造函数注入Angular服务

同时声明一个初始为false的变量isLoaded。

import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [EmployeeService]
})
export class AppComponent {
  title = '';
  emps: [] = [];
  isLoaded:boolean=false;
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {



  }

编写一个返回Employee的方法,一旦API准备好了,就把isLoaded ,设置为true。


  getEmployees(): Promise<Employee>{
      
          this.employeeService.getEmployees().subscribe((data) => {
      this.emps = data;
      this.isLoaded=true;
    }, (error) => {
      console.log("An error accessing Employee Service");
    })

  }
}

在html模板中,使用带有isLoaded的ngIf在API返回数据后加载任何组件或数据。

<div *ngIf="isLoaded"> Load data before component example </div>