如何显示从Angular中的后端API收到的数据

发布于 2025-01-29 03:04:23 字数 2044 浏览 2 评论 0原文

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

我的服务文件:

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

}

lightee.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);
      }
    )
  }
}

结果:

”在此处输入图像描述”

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.

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

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 :

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随梦而飞# 2025-02-05 03:04:24

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

如果您仅在html中使用employeeeobj的数据,则可以在html中使用它,那么您只需检查值是否未定义,并且当数据完成填充时,它将自动更新。

您还可以在getemployeee函数的内部使用雇员进行任何操作。

否则,您可以使用 async/等待

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

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.

You also could just do anything you need to do with your employeeObj inside of your getEmployee function.

Otherwise you can make use of 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);
    });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文