Issue
I'm trying to get the details of a single post but i keep getting this error; ERROR TypeError: Cannot read property 'title' of undefined at Object.eval [as updateRenderer]. Although the data is being gotten correctly in console.log but its not showing on the page itself. when i do {{post?.title}}, the error goes away but the results still don't appear on the page but shows correctly in console.log
Ionic Framework: v4 OS Platform: Windows 10
post.service
getAllPosts(): Observable<any> {
return this.http.get(`${this.url}`).pipe(
map(results => {
console.log('Raw: ', results);
return results['posts'];
})
);
}
getPost(postId: string) {
return this.http.get(`${this.url}/${postId}`);
}
post.page.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { PostService } from '../post.service';
@Component({
selector: 'app-post',
templateUrl: './post.page.html',
styleUrls: ['./post.page.scss'],
})
export class PostPage implements OnInit {
loadedPost: any;
constructor(private activatedRoute: ActivatedRoute, private postService: PostService) { }
ngOnInit() {
const postId = this.activatedRoute.snapshot.paramMap.get('postId');
this.postService.getPost(postId).subscribe(result => {
console.log('details: ', result);
this.loadedPost = result;
});
}
}
post.page.html
<ion-card-header>
<ion-card-title text-center>{{loadedPost.title}}</ion-card-title>
</ion-card-header>
console.log output
post:
author_id: 0
body: "<p>This is the body of the lorem ipsum post</p>"
category_id: null
created_at: "2019-06-13 17:08:45"
excerpt: "This is the excerpt for the Lorem Ipsum Post"
featured: 0
id: 1
image: "posts/post1.jpg"
meta_description: "This is the meta description"
meta_keywords: "keyword1, keyword2, keyword3"
seo_title: null
slug: "lorem-ipsum-post"
status: "PUBLISHED"
title: "Lorem Ipsum Post"
screenshot of console.log: Screenshot of console.log response
Solution
Based on the image of the console.log(result)
seems like the response is something like this:
{
"post": {
"title": "..."
}
}
So you'd need to assign your loadedPost
like this:
// ...
this.postService.getPost(postId).subscribe((result: any) => {
console.log('post: ', result.post);
this.loadedPost = result.post; // <----- I've changed this!
});
And then show the title like this:
<ion-card-header>
<ion-card-title text-center>{{ loadedPost?.title }}</ion-card-title>
</ion-card-header>
Please notice that the ?
in {{ loadedPost?.title }}
is needed because the loadedPost
property is assigned by an async method, so it will be undefined
at first until the API returns the response.
Answered By - sebaferreras
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.