我如何在 angular 中显示从后端 api 收到的数据

how can i show the data received from backend api in angular

我目前正在尝试显示员工登录帐户后的数据,我可以通过他的用户名从后端获取员工的数据,我可以控制台记录它,但是当我将数据分配给另一个类型为 any 的变量我控制台记录该变量,结果我得到了 undefined。

我的服务文件:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Employee } from '../Employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private apiServerUrl = environment.apiBaseUrl;

  constructor(private http: HttpClient) { }

  getEmployee(username: String): Observable<any> {
    return this.http.get<any>(`${this.apiServerUrl}/getbyuser/${username}`);
  }

}

employee.component.ts 文件

import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { EmployeeService } from '../services/employee.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  constructor(public auth: AuthService,private api: EmployeeService) { }

  employeeObj : any;
  ngOnInit(): void {
    let username = localStorage.getItem('username');
    if(username != null) {
      this.getEmployee(username);
      console.log(this.employeeObj); // it shows undefined 
    } 
  }

  getEmployee(username: String) {
    this.api.getEmployee(username).subscribe(
      (data) => {
        this.employeeObj = data; 
        console.log(this.employeeObj); // it shows the informations i received from my backend
      }, (error: HttpErrorResponse) => {
        console.log(error);
      }
    )
  }
}

结果:

这是由于代码的异步执行导致在实际分配值之前记录变量。 这个问题可能有多种解决方案,但这取决于您实际想用代码做什么。

如果您只在 HTML 中使用来自 employeeObj 的数据,那么您可以简单地检查该值是否未定义,当数据完成填充时它会自动更新。

您也可以在 getEmployee 函数中使用 employeeObj 做任何您需要做的事情。

否则你可以利用promises and async/await

ngOnInit(): void {
  let username = localStorage.getItem('username');
  if(username != null) {
    this.getEmployee(username);
    console.log(this.employeeObj);
  } 
}

async getEmployee(username: String) {
  this.employeeObj = await this.api.getEmployee(username).toPromise()
    .catch((error: HttpErrorResponse) => {
      console.log(error);
    });
}