[英]On angular 8 refreshing a page doesn't show the data from backend 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
做任何您需要做的事情。
否则你可以使用Promise和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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.