繁体   English   中英

如何以角度显示从后端 api 接收到的数据

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

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

我的服务文件:

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

}

员工.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做任何您需要做的事情。

否则你可以使用Promiseasync/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);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM