簡體   English   中英

如何使用Angular2中的Observable Map函數將Http Service返回的Response對象映射到TypeScript對象

[英]How to Map Response object returned by Http Service to a TypeScript Objects using Observable Map function in Angular2

您好我已經創建了一個angular2服務,其任務是調用webapi,它返回json對象結構中的數據,如下所示:

//Result of the webapi service call.
{
  "Total":11,
  "Data":[{"Id":1,"Name":"A","StartDate":"2016-01-01T00:00:00"},
     {"Id":2,"Name":"B","StartDate":"2016-02-01T00:00:00"}]
}

這是我的angular2服務。 getMileStones方法工作得很好,我能夠將響應轉發回MileStone []。 但是為了獲取分頁數據,我創建了一個函數getPagedMileStones(int,int),它調用webapi方法並返回結果如上所述結構。我想將返回的響應從webapi強制轉換為IPagedResponse。 但我無法使其正常工作。 我有一個接口IPagedResponse,我希望此函數將此信息返回給組件調用,以便我可以提供分頁功能。

    import { MileStoneModel} from './milestoneModel'
    import { Http, Response, Headers, RequestOptions } from '@angular/http'
    import { Injectable } from '@angular/core'
    import { Observable }     from 'rxjs/Observable';

    import {PaginatePipe, PaginationService, PaginationControlsCmp, IPaginationInstance} from 'ng2-pagination';
    import 'rxjs/Rx';

    export interface IPagedResponse<T> {
        total: number;
        data: T[];
    }

    export interface DataModel {
        id: number;
        data: string;
    }

    @Injectable()
    export class MileStoneService //implements IPagedResponse<MileStoneModel>
    {

        data: MileStoneModel[];
        //private _page: number = 1;
         total: number;

        private pagedResult:  IPagedResponse<MileStoneModel>;

        mileStones: MileStoneModel[]
        private url: string = "http://localhost/ControlSubmissionApi/api/Milestones";
        constructor(private http: Http) {


        }
        getMilestones(): Observable< MileStoneModel[]> {

            return this.http.get(this.url)
                .map((response: Response) => <MileStoneModel[]>response.json())            
                .catch(this.handleError);


        }
        //----------- Starts here -------------
        getTypedPagedMilestones(page: number, pageSize: number) {
            debugger;
            return this.http.get(this.url + "/" + page + "/" + pageSize)
                .map((res: Response) => { this.data = <MileStoneModel[]>res.json().Data; this.total = res.json().Total; })
                //.map((Data, Total) => { console.log(Data); console.log(Total); })
                .catch(this.handleError);
        //----------- Ends here ------------

        }

        getMilestone(id: number):Observable< MileStoneModel> {

            return this.http.get(this.url+"/"+id)
                .map((response: Response) => <MileStoneModel>response.json())
                .catch(this.handleError);

        }
        searchMileStones(name: string): Observable<MileStoneModel[]> {
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            return this.http.get(this.url+"/search/"+name)
                .map((response: Response) => <MileStoneModel[]>response.json())
                .catch(this.handleError);
        }
        addMileStone(formdata:string) {
            //let body = JSON.stringify({ newMileStone });
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });

            return this.http.post(this.url, formdata, options)
                .map((response: Response) => <MileStoneModel>response.json())        
                .catch(this.handleError);

        }
        private handleError(error: any) {
            // In a real world app, we might use a remote logging infrastructure
            // We'd also dig deeper into the error to get a better message
            let errMsg = (error.message) ? error.message :
                error.status ? `${error.status} - ${error.statusText}` : 'Server error';
            console.log(errMsg); // log to console instead
            return Observable.throw(errMsg);
        }
    }

這不行嗎? 我沒有在您的代碼中看到任何類型的IPagedResponse變量

    pageResponse: IPagedResponse<MileStoneModel>;

    getTypedPagedMilstones(page: number, pageSize: number): Observable<IPagedResponse<MileStoneModel>> {
        return this.http.get(this.url + "/" + "/" + pageSize)
            .map((res: Response) => {
                this.pageResponse.data = <MileStoneModel[]>res.json();
                this.pageResponse.total = res.json().Total;
            })
            .catch(this.handleError);
    }
getPagedMilestones(page: number, pageSize: number): Observable<IPagedResponse<MileStoneModel>> {

    return this.http.get(this.url + "/" + page + "/" + pageSize)
        .map((response: Response) => {
            return {
                data: <MileStoneModel[]>response.json().Data,
                total: response.json().Total
            }
        })
        .catch(this.handleError);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM