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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With