0

I was trying to practice on Angular, I am having trouble with get requests types Angular Stackblitz

import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable, throwError } from 'rxjs';



@Injectable({
  providedIn:'root'
})
export class PostsService {

  constructor(private http:HttpClient) { }
  getPosts():Observable<Post[]>{
    return this.http.get<any>('https://dummyjson.com/posts').pipe(
    map(res=> res.posts),
      catchError(err=>{
        console.log(err)
        return throwError(()=>err)
      })
    )
  }
}
interface PostResponse{
  limit: number
  posts: string[]
  skip: number
  total: number
}
interface Post {
  body: string
id: number
reactions: number
tags: string[]
title: string
userId: number
}

Generally I bypass this with any type instead of PostResponse or Post[] but I think it is not the best practice, map operator makes things more complicated I suppose. So what should get requests type be in this kind of situation?

2
  • 1
    I'm confused, why aren't you using the data structures defined above? Commented Dec 28, 2022 at 19:55
  • When I used them, they gave me type error, I tried both, API response return an object but I need just ' posts' , check Stackblitz, you can see errors Commented Dec 28, 2022 at 20:05

1 Answer 1

2

Your problem is that you are declaring the posts property of the PostResponse as type string[], but it should be type Post[]:

interface PostResponse {
  limit : number;
  skip  : number;
  total : number;
  posts : Post[];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.