Home > other >  Angular creating service with get request using HttpClient, question with types of get request
Angular creating service with get request using HttpClient, question with types of get request

Time:12-29

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?

CodePudding user response:

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[];
}
  • Related