Reputation: 41
I try to get data from my server. Inside my subscribe function I have data but when i try to use it outside function console.log return undefined
Service:
getPostDetail():Observable<Post> {
return this.http.get<Post>(this.detailPostUrl);
}
Component:
export class PostDetailComponent implements OnInit {
post: Post;
constructor(private postsService:PostsService) {
this.postsService.getPostDetail().subscribe(data => {
this.post = data;
console.log(this.post);
});
}
ngOnInit(): void {
console.log(this.post); // undefined
}
}
I see that first I get a undefined
from ngOnInit
's console.log()
but I don't know how to change it.
I can add that I have very similar function and that one works.
Anyone can help ?
Upvotes: 2
Views: 1448
Reputation: 2248
As the comments above indicate, http calls are asynchronous, meaning it takes some time for their results to come back from the service call. The getPostDetail() subscription in the constructor does not block execution, and the ngOnInit() method will be called before any data comes back. That's why this.post is undefined.
Instead, I would put the call to getPostDetail() in ngOnInit, and put any logic that requires this.Post in the subscription handler, as Pierterjan recommends.
If your UI is expecting to bind to this.Post, then you should use the elvis operator:
<div>{{Post?.postDate}}</div>
This will not throw an error while Post is null or undefined. It just won't display until the service call completes.
Upvotes: 1