Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught (in promise): Error: Cannot read property of undefined

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?

like image 813
Weit Avatar asked Sep 15 '16 09:09

Weit


People also ask

What is cannot read property'then'of undefined?

When you run this code in the browser console, you will get an error: TypeError - Cannot read property 'then' of undefined is thrown when the caller is expecting a Promise to be returned and instead receives undefined. Let's consider the above examples.

Why am I getting error uncaught (in promise) in userpagecomponent?

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.

What is undefined error in JavaScript?

Out of the six primitive types defined in JavaScript, namely boolean, string, symbol, number, Null, and undefined, no other type throws as many errors as Undefined. The error most often than not is faced when the scripts come across uninitialized variable or object. ‘Undefined’ is the property of the global object.

Why is my promise not returning?

And the TypeError indicates you are calling then () on undefined, which is a hint that the Promise itself is undefined. The next step is to go and debug the code to figure out why a Promise is not returned. We looked at two different code examples to see what can potentially cause this error and how to resolve it.


1 Answers

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

like image 57
obenjiro Avatar answered Oct 17 '22 08:10

obenjiro