Home > database >  Does not display a separate post
Does not display a separate post

Time:12-28

I need your help. I take data from the JSON placeholder resource, display posts and try to make each post have a posts-details page and open this page instead of all posts. As a dynamic page for each post. However, I'm getting errors in the posts-details.component.ts file that look like this:

TS2322: Type 'IPost[]' is not assignable to type 'IPost'., TS2739: Type 'IPost[]' is missing the following properties from type 'IPost': id, title, body

Please help with this problem. I will be very grateful

posts-details.component

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {IPost} from "../models/posts";
import {PostService} from "../services/post.service";

@Component({
selector: 'app-post-details',
templateUrl: './post-details.component.html',
styleUrls: ['./post-details.component.css']
})

export class PostDetailsComponent implements OnInit {

fullPost: IPost

constructor(private activatedRoute: ActivatedRoute, private postService: PostService) {
this.activatedRoute.params.subscribe(params => {
  this.postService.getDifferentPost(params['id']).subscribe(value => this.fullPost = value)
})
}

ngOnInit(): void {}
}

post.service.ts

import {HttpClient} from "@angular/common/http";
import { Injectable } from '@angular/core';
import {Observable} from "rxjs";
import {IPost} from "../models/posts";

@Injectable({
providedIn: 'root'
})

export class PostService {

private url = `https://jsonplaceholder.typicode.com/posts`

constructor(private httpClient: HttpClient) { }

getPosts(): Observable<IPost[]> {
return this.httpClient.get<IPost[]>(this.url)
}

getDifferentPost(id: number): Observable<IPost[]> {
return this.httpClient.get<IPost[]>(this.url   '/'   id);
}

}

my routes in app,module.ts file

let routes: Routes = [
{path: 'users', component: UsersComponent, children: [{path: ':id', component: UserDetailsComponent}]},
{path: 'posts', component: PostsComponent},
{path: 'posts/:id', component: PostDetailsComponent},
]

post.ts

export interface IPost {
id: number,
title: string,
body: string
}

posts-details.component.html

<div *ngIf="fullPost">
{{fullPost.title}}
{{fullPost.body}}
</div>

CodePudding user response:

You are expecting IPost array from the service, but you are adjusting the service response into singular IPost element. You should handle as this:

fullPost: IPost[]

constructor(private activatedRoute: ActivatedRoute, private postService: PostService) {
  this.activatedRoute.params.subscribe(params => {
     this.postService.getDifferentPost(params['id']).subscribe(value => this.fullPost = value)
  })
}

and also in your html file :

<div *ngFor="let post of fullPost">
{{post.title}}
{{post.body}}
</div>
  • Related