I'm working with Angular 5 and Contentful API. I've have a rather strange issue I believe.
I'm creating a blog post app, I have a post.component and a post-detail.component. I can get a list of post and show them in my template.
I pass on the data to the detail by a service and I can show the entire post. I have set up the router to go to base/detail/:id and it is working.
I want to be able to send somebody the url and they'll see the detailed post, but the service cannot deliver the data when starting at that component. In my OnInit I've made an If-Else, and I see the postId printed in the console correctly, but when logging the object I get undefined. Is this an asynchronous problem or?
Post-detail.component.ts:
if (this.dataService.serviceData == null) {
this.route.params.subscribe(params => {
this.postId = params['id'];
});
console.log('post id: ' + this.postId);
this.getContent(this.postId).then(data => this.post = data);
console.log(this.post);
}
else {
this.post = this.dataService.serviceData;
}
I do the exact same in another component, and it works like a charm, except I've not packed it in an If-Else. The two objects however are different in size the one contains image, the other one working does not - the list does too contain images but no problem here.
When asking for both ids in the other component I can use it in my template.
<div *ngIf="post">
<mat-card >
<mat-card-header>
<mat-card-title>
<h1>{{ post.fields.headline }} </h1>
</mat-card-title>
</mat-card-header>
<img style="max-width:100%" *ngFor="let img of post.fields.media" src="{{ img.fields.file.url }}" />
<mat-card-content>
<span [innerHTML]="post.fields.content | mdToHtml"> </span>
</mat-card-content>
<mat-card-footer>
<time>
Opdateret: {{ post.sys.updatedAt | date: 'shortDate'}}
</time>
</mat-card-footer>
</mat-card>
</div>
You've correctly guessed its an async issue. You need to use the postId
in the same scope where you're setting it (same goes for this.Post
), like so:
if (this.dataService.serviceData == null) {
this.route.params.subscribe(params => {
this.postId = params['id'];
console.log('post id: ' + this.postId);
this.getContent(this.postId).then(data =>
{
this.post = data;
console.log(this.post);
});
});
}
else {
this.post = this.dataService.serviceData;
}