Angular - HttpClient: Map Get method object result to array property

后端 未结 5 615
忘了有多久
忘了有多久 2021-02-04 06:19

I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my service call works.

5条回答
  •  悲哀的现实
    2021-02-04 06:47

    There are 2 approaches of doing this. You can use .map operator form the observable to map one type of observable into another and second approach includes just with the help of interface.

    1st Approaches (with the help of .map)

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    import { Observable } from 'rxjs/Observable';
    
    import 'rxjs/add/operator/map';
    
    interface ItemsResponseObj {
        id: string,
        modified: string,
        name: string
    }
    
    interface ItemsResponse {
        shows: Array;
    }
    
    @Injectable()
    export class AppService {
    
        constructor(private http: HttpClient) { }
    
        getData(): Observable {
            return this.http.get('api/api-data.json')
                .map(res => res.shows);
        }
    
    }
    

    and in the 2nd approach with the help of wrapping interfaces

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    import { Observable } from 'rxjs/Observable';
    
    interface ItemsResponseObj {
        id: string,
        modified: string,
        name: string
    }
    
    interface ItemsResponse {
        shows: Array;
    }
    
    @Injectable()
    export class AppService {
    
        constructor(private http: HttpClient) { }
    
        getData(): Observable {
            return this.http.get('api/api-data.json')
        }
    
    }
    

提交回复
热议问题