17

Component take user from service with params

@Component({
    selector: 'users',
    providers: [UserService],
    template: `
    <p>{{user.id}}</p>
`
})
export class UserPageComponent implements OnInit  {
    constructor(
        private userService: UserService,
        private route: ActivatedRoute
    ) {};

    ngOnInit(): void {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];
            this.userService.getUser(id)
                .then(user => {console.log(user.id);this.user = user})
        });
    }

Service :

@Injectable()
export class UserService {
    private postUrl = 'http://127.0.0.1:8000/user-detail/';  // URL to web api
    constructor(private http: Http) {
    }

    getUser(id: number): Promise<User> {

        return this.http.get(this.postUrl+id)
            .toPromise()
            .then(response => response.json() as User)
            .catch(this.handleError);

    };

And I get Error Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined

It looks as if the service does not send the promise, although it should. How to solve this proble?

Weit
  • 571
  • 1
  • 6
  • 20

1 Answers1

24

It looks like your component doesn't have default value for user, so it is undefined when component rendered try adding default value

@Component({
    selector: 'users',
    providers: [UserService],
    template: `
    <p>{{user.id}}</p>
`
})
export class UserPageComponent implements OnInit  {
    user = {} // default value for user

    constructor(
        private userService: UserService,
        private route: ActivatedRoute
    ) {};

    ngOnInit(): void {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];
            this.userService.getUser(id)
                .then(user => {console.log(user.id);this.user = user})
        });
    }

actually it will be better to add some conditional logic here then

<p *ngIf="user">{{user.id}}</p>

it should work

Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
obenjiro
  • 3,665
  • 7
  • 44
  • 82
  • You may as well add a conditional(ternary operator) denoted by the question mark symbol ?. This expression {{user.id}} will execute only if the condition is truthy – Collins USHI Jan 04 '22 at 02:40