我正在尝试在模板中显示Object。在控制台 Users.email 正在运行,但在模板中它不起作用。是否必须定义Users对象的类型。如何正确处理响应。控制台数据显示为用户的对象,我将第一个对象作为数据[0]。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from './services/authentication.service';
import { EmployeeService } from './services/emplyee.service';
@Component({
template: `<h2>Welcome, {{ Users.email }}</h2>
<button class="btn btn-info bg-blue bg-darken-2 mt-1 min-width-150" (click)="logout()"><i class="icon-unlock2"></i>
Logout
</button>`,
})
export class homeComponent implements OnInit {
Users: any;
constructor(private authenticationService: AuthenticationService,
private router: Router, private
emplyeeService: EmployeeService) {
}
ngOnInit() {
if (!localStorage.getItem('currentUser')) {
this.router.navigate(['/']);
console.log("Go Login");
} else {
this.getUsers();
}
}
logout() {
this.authenticationService.logout();
this.router.navigate(['/']);
}
getUsers() {
this.emplyeeService.getAll()
.subscribe(
(data: any) => {
console.log(data);
this.Users = data[0];
console.log(this.Users.email);
},
(error) => console.log(error)
);
}
}
答案 0 :(得分:2)
您使用Observables所以数据会有一点延迟,因此您需要输入安全操作数 ?
,如下所示
<h2>Welcome, {{ Users?.email }}</h2>