Home > Net >  Cannot read properties of undefined (reading 'name') Angular
Cannot read properties of undefined (reading 'name') Angular

Time:12-21

I need your help. Now I'm trying to deal with routes in Angular. I took the data from JSON placeholder. I'm trying to display user details. Everything works for me, but in the console I get this error Cannot read properties of undefined (reading 'name')

When I use the pipe in the file user-details.component.ts, everything works for me, I get a json object, but when I want to output a separate field from the model, I get an error. The data types from the model correspond to the data type from the json url.

What am I doing wrong? Thank you very much

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})
}
}

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 {}
}

user-details.component.html

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

CodePudding user response:

Most likely your userservice has not returned the result yet and fulluser is undefined. Try this:

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