what is the best practice for getting response model manipulation?

Viewed 121

I new to Angular 8, and im trying to understand what is the best way to recive the response from the backend (in a specific form) and getting from it what i need. so, i wrote a s service that is responsible for sending and receiving requests & responds - this is the steps i thought of:

  1. get the response
  2. create a Response object that will save the response.
  3. pass the Data property (Project[]) to the component.

what im missing is what is the best practice to do this steps and if it should be in the service?

this is my response from the server:

{
    "statusCode": 200,
    "errorMessage": null,
    "data": [
        {
            "id": 7,
            "name": "yul",
            "company": "ff",
            "repository": "https://www.google.com/search?",
            "bugsnagKey": null,
            "imageUrl": "https://encrypted-tbn0.gstatic.com/images"
        },
        {
            "id": 8,
            "name": "aa2",
            "company": null,
            "repository": "cc2",
            "bugsnagKey": null,
            "imageUrl": "b2b"
        }  
    ]

this is my response model:

import { Project } from '../../pages/projects/models';

export class Response {
  StatusCode: number;
  ErrorMessage: string;
  Data: Project[];

  constructor(_StatusCode, _ErrorMessage, _Data) {
    this.StatusCode = _StatusCode;
    this.ErrorMessage = _ErrorMessage;
    this.Data = JSON.parse(JSON.stringify(_Data));
  }
}

this is the api service:

export class ProjectService {
  dbUrl: string;

  constructor(private http: HttpClient) {
    this.dbUrl = environment.dbUrl;
  }

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  };

  getProjects(): Projects[] {
    this.http.get<Response>(this.dbUrl).pipe(  
    )

 }

2 Answers

I would map the response in the service and subscribe inside the component.

export class ProjectService {
  dbUrl: string;

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  };

  constructor(private http: HttpClient) {
    this.dbUrl = environment.dbUrl;
  }

  getProjects(): Observable<Projects[]> {
    return this.http.get<Response>(this.dbUrl).pipe(
        map(response => response.Data),
    )
  }
}

my mistake was that i defined the response type as 'Response' - when its not the actual type - once i changed it to 'any' , i could create a 'Response' object correctly, and pass the Data property with success

  getProjects():  Observable<Project[]> {
    return this.http.get<any>(this.dbUrl).pipe(
      map((response: any) => new Response(response.statusCode, response.errorMessage, response.data).Data,
    ));
  }

Related