Angular 4 the correct way to drop an HTTP response

I created a service in Angular 4 and I am retrieving data via REST / JSON (new to Angular) using this code:

Interface

export interface IItem {
    Id: number;
    Title: string;
}

Service

import { IItem } from './item';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

@Injectable()
export class ItemTest {

    constructor(private _http: HttpClient) {}

    getItems(): Observable<IItem[]> {
        return this._http.get<IItem[]>('url')
            .do(data => {
                console.log(data);
            })
    }
}

HTTP cast to IITem works fine if the response is in this format

[
    {
        "Id": 53,
        "Title": "Test Document 4.docx"
    },
    {
        "Id": 55,
        "Title": "Test Document 2.docx"
    }
]

But the actual response from the server looks like this, and the cast does not work. What is the best way to attribute part of the results to the IItems array?

{
    "d": {
        "results": [
            {
                "Id": 53,
                "Title": "Test Document 4.docx"
            },
            {
                "Id": 55,
                "Title": "Test Document 2.docx"
            }
        ]
    }
}
-1
source share
3 answers

Do you want to use the map operator:

@Injectable()
export class ItemTest {

    constructor(private _http: HttpClient) {}

    getItems(): Observable<IItem[]> {
        return this._http.get('url').map((data) => data['d']['results'])              
            .do(data => {
                console.log(data);
            })
    }
}
+1
source

You will probably want to run several display utilities.

http.get(url)
.map(response => response.json())
.map(response => response.d.results)
.map(results => results.map(item => return Object.create(IItem, item))
0
source

get JSON, . , , . :

getItems(): Observable<IItem[]> {
    return this._http.get<{ d: { results: IItem[] } }>('url')
        .map(response => response.d.results)
        .do(data => {
            console.log(data);
        }):
}

, , .


:

.get<IItem[]>(...)
.map((data) => data['d']['results']) 

, , any, . , , .

-2

Source: https://habr.com/ru/post/1687924/


All Articles