You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular ngOnInit中获取的后端数据如何渲染到HTML模板 报错如何解决

错误原因及修复方案

1. 修复NG8003模板指令错误

你写错了*ngIf的语法前缀,模板中的#ngIf需要改为*ngIf。
#是Angular模板引用变量的标识,你写的#ngIf="userDetails"会被识别为创建名为ngIf的模板变量,同时尝试绑定userDetails作为值,才会触发找不到对应导出指令的报错。

2. 修复TS2339属性不存在错误

你在ts文件中错误将userDetails初始化为空数组[],TypeScript会自动推断它的类型为never[],但你实际接口返回的res['user']是包含name、email属性的对象,类型不匹配导致访问属性时抛出错误。


修改后代码

component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from '../shared/user.service';
import { Router } from '@angular/router';

// 可按需补充更多用户属性
interface User {
  name: string;
  email: string;
}

@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: User = {} as User;

  ngOnInit(): void {
    this.userService.getUserProfile().subscribe(
      (res:any)=>{
        this.userDetails = res['user'];
      },
      err=>{}
    );
  }

  onLogout(){
    this.userService.deleteToken();
    this.router.navigate(['/login']);
  }

}

component.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>

内容的提问来源于stack exchange,提问作者Tanmay joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:06:02