I am currently working on a service that retrieves a post from a JSON file containing an array of posts. I already have a service in place that uses HttpClient
to return the contents of a JSON file. The main objective is to display the full content of the post.
Here is the service responsible for retrieving the JSON file:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetJsonFileService {
constructor(private http: HttpClient) {}
getJsonFile(jsonFile: string /* the file path is set by components */) {
return this.http.get(jsonFile,{observe: 'body', responseType: 'json'});
}
}
And here is the service designed to retrieve a specific post by its ID:
import { Injectable } from '@angular/core';
import { GetJsonFileService } from './get-json-file.service';
@Injectable({
providedIn: 'root'
})
export class GetPostService {
constructor(private getJsonFileservice: GetJsonFileService) {}
getPost(id: number): object {
let post!: object;
this.getJsonFileservice.getJsonFile('assets/posts.json').subscribe((data: any) => {
post = data["posts"][id];
});
return post;
}
}
Lastly, we have the component responsible for displaying the post:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GetPostService } from '../services/get-post.service';
@Component({
selector: 'app-post-view',
templateUrl: './post-view.component.html',
styleUrls: ['./post-view.component.scss']
})
export class PostViewComponent implements OnInit {
_post!: object;
id!: number;
constructor(private route: ActivatedRoute, private getPost: GetPostService) {}
ngOnInit() {
let id!: number;
this.route.params.subscribe(params => {
id = params.id;
});
this._post = this.getPost.getPost(id);
}
}
When attempting to display something in the component template like:
{{_post.title}}
An error occurs stating:
Errors while compiling. Reload prevented.
In Visual Studio Code, TypeScript points out:
Property 'title' does not exist on type 'object'
I have tried @msanford's solution, but there is still one issue regarding 'posts[\"posts\"][id]' in the post-view component that needs to be addressed. Unfortunately, I am unsure of how to resolve it:
posts["posts"][id]
TypeScript throws an error:
Element implicitly has an 'any' type because expression of type '"posts"' can't be used to index type 'Object'.
Property 'posts' does not exist on type 'Object'
Any suggestions or ideas?