I'm trying to make a service that gets a post from a json file containing array of posts.
i have already a service that returns a json file contents by using HttpClient
.
the goal is to show the full post contents.
the service that gets a 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'});
}
}
the service that gets a 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{
var post!: object;
this.getJsonFileservice.getJsonFile('assets/posts.json').subscribe((data :any)=>{
post = data["posts"][id];
});
return post;
}
}
the component that shows 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(){
var id!: number;
this.route.params.subscribe(params=>{
id = params.id;
});
this._post = this.getPost.getPost(id);
}
}
when i try to show something in the component template like:
{{_post.title}}
i get this error:
Errors while compiling. Reload prevented.
and in vscode typescript tells me this:
Property 'title' does not exist on type 'object'
I Tried @msanford's solution.
there still one thing to change in post-view but i don't really know how to do it:
posts["posts"][id]
typescript gives me 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 ideas?