[英]How to get array data to render in html templete in Angular ngOnInit
I am trying to fetch the info from backend and showing it in Angular components.我正在尝试从后端获取信息并将其显示在 Angular 组件中。 But I am fetching it in ngOnInit first before rendering but it is showing me error in angular.
但是我在渲染之前先在 ngOnInit 中获取它,但它在 angular 中显示错误。 This is my component.ts file
这是我的 component.ts 文件
import { Component, OnInit } from '@angular/core';
import { UserService } from '../shared/user.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor( private userService: UserService, private router: Router) { }
userDetails = [];
ngOnInit(): void {
this.userService.getUserProfile().subscribe(
(res:any)=>{
this.userDetails = res['user'];
},
err=>{}
);
}
onLogout(){
this.userService.deleteToken();
this.router.navigate(['/login']);
}
}
This is my component.html file这是我的组件。html 文件
<table #ngIf="userDetails" class="table-fill">
<thead>
<tr>
<th colspan="2" class="text-center">
User Profile
</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name</td>
<td>{{userDetails.name}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{userDetails.email}}</td>
</tr>
<tr>
<td colspan="2" class="text-center">
<input type="button" (click)="onLogout()" value="Logout">
</td>
</tr>
</tbody>
</table>
This is the error I am getting这是我得到的错误
Error: src/app/home/home.component.html:1:15 - error NG8003: No directive found with exportAs 'userDetails'.
1 <table #ngIf="userDetails" class="table-fill">
~~~~~~~~~~~
src/app/home/home.component.ts:7:16
7 templateUrl: './home.component.html',
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component HomeComponent.
Error: src/app/home/home.component.html:12:31 - error TS2339: Property 'name' does not exist on type 'never[]'.
12 <td>{{userDetails.name}}</td>
~~~~
src/app/home/home.component.ts:7:16
7 templateUrl: './home.component.html',
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component HomeComponent.
Error: src/app/home/home.component.html:16:31 - error TS2339: Property 'email' does not exist on type 'never[]'.
16 <td>{{userDetails.email}}</td>
~~~~~
src/app/home/home.component.ts:7:16
7 templateUrl: './home.component.html',
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component HomeComponent.
Help me.帮我。 I have tried a lot but it is not working
我已经尝试了很多但它不起作用
you are accessing userDetails as an Object.So, replace您正在访问 userDetails 作为 Object.所以,替换
userDetails = [] as userDetails:any;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.