Parth Savadiya
Parth Savadiya

Reputation: 1211

Tightly coupled map server response list with typescript class in Angular 7

I think it should be easy but I couldn't figure out a decent solution to it. Here is a demo which illustrates what is my requirement: https://stackblitz.com/edit/angular-zjxvuh

I'm getting a response from the server like this:

[{"userId":10,"id":197,"title":"dignissimos quo nobis earum saepe","completed":true},{"userId":10,"id":198,"title":"quis eius est sint explicabo","completed":true},{"userId":10,"id":199,"title":"numquam repellendus a magnam","completed":true}]

And my typescript class looks like:

export class PostData {
  public id?: number;
  public title?: number;
}

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { PostData } from './post';
import { map, tap } from "rxjs/operators";
import { Observable } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';
  postData: PostData;
  constructor(private http: HttpClient) { }


  ngOnInit(): void {

    var data = this.getFoo().subscribe(data => {
        console.log("data",JSON.stringify(data))
    });
    //console.log(data);
  }

  getFoo(): Observable<PostData[]> {
		return this.http.get<PostData[]>      ('https://jsonplaceholder.typicode.com/todos')
      .pipe(map(res => {
           return res as PostData[];
        })
      )
	}
}

I want server response in Post type array I mean I don't want that extra fields that coming from the server. How do I get rid of those extra fields?

Upvotes: 0

Views: 171

Answers (2)

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

 ngOnInit(): void {
    var data = this.getFoo().subscribe((resp: PostData[]) => {
      console.log("data", JSON.stringify(resp))
    })
  }


  getFoo(): Observable<PostData[]> {
    return this.http.get<PostData[]>('https://jsonplaceholder.typicode.com/todos')
  }

Upvotes: 0

wentjun
wentjun

Reputation: 42516

You can amend your getFoo() method to return only the required fields. One of the ways to do it would be to make use of Array.map()

getFoo(): Observable<PostData[]> {
  return this.http.get<PostData[]>('https://jsonplaceholder.typicode.com/todos')
    .pipe(
      map(res => {
        const data = res.map(obj => <PostData>{
          id: obj.id,
          title: obj.title
        });
        return data;
      })
    );
}

This way, on your ngOnInit() when you return the observable and console.log() it, you will only be an array consisting of PostData objects with the id and title properties.

this.getFoo().subscribe(data => { 
    console.log(JSON.stringify(data));
});

In addition, I would recommend you to use an interface, rather than class. For this scenario, try not to leave the properties as optional.

export interface PostData {
  id: number;
  title: string;
}

Upvotes: 1

Related Questions