无法读取未定义的属性(读取 'name')Angular

Cannot read properties of undefined (reading 'name') Angular

我需要你的帮助。现在我正在尝试处理 Angular 中的路线。我从 JSON 占位符中获取数据。我正在尝试显示用户详细信息。一切都对我有用,但在控制台中出现此错误 Cannot read properties of undefined (reading 'name')

当我在文件 user-details.component.ts 中使用管道时,一切都对我有用,我得到了一个 json 对象,但是当我想从模型中输出一个单独的字段时,我得到一个错误。模型中的数据类型对应于 json url.

中的数据类型

我做错了什么?非常感谢

users.component.ts

import {IUser} from "../models/user";
import { Component, OnInit } from '@angular/core';
import {UserService} from "../services/user.service";

@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

users: IUser[]

constructor(private userService: UserService) { }

ngOnInit(): void {
this.userService.getUsers().subscribe(value => this.users = value);
}

}

user.component.ts

import { Component, OnInit, Input } from '@angular/core';
import {IUser} from "../models/user";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})

export class UserComponent implements OnInit {

@Input()
user: IUser

constructor(private router: Router, private activatedRoute: ActivatedRoute) { }

ngOnInit(): void {}

goToDetails():void {
this.router.navigate([this.user.id],{relativeTo: this.activatedRoute, state: this.user})
}
}

用户-details.component.ts

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {IUser} from "../models/user";

@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.css']
})

export class UserDetailsComponent implements OnInit {

fullUser: IUser;

 constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.activatedRoute.params.subscribe(params => {
  this.fullUser = this.router.getCurrentNavigation()?.extras.state as IUser
})
}
ngOnInit(): void {}
}

用户-details.component.html

<div>
<!--{{fullUser | json}}-->
{{fullUser.name}}
</div>

很可能你的用户服务还没有返回结果并且 fulluser 是未定义的。试试这个:

<div *ngIf="fullUser">
 <!--{{fullUser | json}}-->
 {{fullUser.name}}
</div>

ngif 不需要,它会检查对象是否存在并且看起来确实存在,所以这应该行不通?最佳实践你应该为你的对象创建一个用户模型->

export interface User {
  name: string;
}

然后导入并使用模型定义,在这种情况下名称已定义

或丑陋的试用修复 ->

{{ user["fullUser"] && user["fullUser"]?.name}}