简体   繁体   English

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

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

Im currently trying to show the data of an employee after he loggin to his account, i can get the data of the employee from the backend by his username and i can console logged it , but when i assign the data to another variable of type any i console log that variable and i got undefined as a result.我目前正试图在员工登录到他的帐户后显示他的数据,我可以通过他的用户名从后端获取员工的数据,并且我可以控制台记录它,但是当我将数据分配给另一个类型为 any 的变量时我控制台记录了那个变量,结果我得到了未定义的结果。

my service file :我的服务文件:

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 file员工.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);
      }
    )
  }
}

the result :结果 :

在此处输入图像描述

This is due to the asynchronous execution of the code which causes the variable to be logged before the value has actually been assigned.这是由于代码的异步执行导致在实际分配值之前记录变量。 There could be multiple solutions to this problem, but it depends on what you actually want to do with your code.这个问题可能有多种解决方案,但这取决于您实际想要对代码执行的操作。

If you are only using data from employeeObj in the HTML after pulling it, then you could simply just check if the value is undefined and it will automatically updated when the data finishes populating.如果您在拉取数据后仅在 HTML 中使用来自employeeObj的数据,那么您只需检查该值是否未定义,它会在数据填充完成时自动更新。

You also could just do anything you need to do with your employeeObj inside of your getEmployee function.您也可以在getEmployee函数中对您的employeeObj做任何您需要做的事情。

Otherwise you can make use of promises and async/await否则你可以使用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.

相关问题 在 angular 8 上刷新页面不显示来自后端 api 的数据 - On angular 8 refreshing a page doesn't show the data from backend api Angular 5如何处理从后端收到的HTML - Angular 5 how to handle HTML received from backend 我希望我的组件在角度2中未从api接收不到数据时不渲染 - I want my component not to render if data is not received from api in angular 2 如何从 API 正确使用 ng2 图表和 Angular 显示数据 - How can I show data using ng2 charts and Angular correctly from an API 仅在从REST API接收数据后,我应该如何使用分页呈现Angular MatTable? - How should I render a Angular MatTable with pagination only after data is received from a REST API? Angular HttpModule如何处理从远程API接收的不适当的数据 - angular HttpModule how to handle inappropriate received data from a remote API 如何将从API接收的数据转换为angular 5中的JSON格式 - How to convert data received from API to JSON format in angular 5 Mat-autocomplete 显示从服务器收到的上一个日期,但不是最新的。 如何修复它以显示收到的最新数据? - Mat-autocomplete is showing the previous date received from the server but not the latest. How can I fix it to show the latest data received? 如何显示在角度/ typescript UI处从后端收到的Java地图数据? - How to display java map data received from backend at angular /typescript UI? 我如何更改来自后端 Angular REST API 的格式? - How i can change the format coming from backend Angular REST API?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM