简体   繁体   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

Hi I have created an angular2 service whose task is to call a webapi which returns data in a json object structure as follows: 您好我已经创建了一个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"}]
}

Here is my angular2 service. 这是我的angular2服务。 The getMileStones methods work perfectly and I am able to cast the response back to MileStone[] . getMileStones方法工作得很好,我能够将响应转发回MileStone []。 But In order to get the paged data I have created a function getPagedMileStones(int,int) which call a webapi method and return the result as mentioned above structure .I want to cast the returned response from webapi to IPagedResponse. 但是为了获取分页数据,我创建了一个函数getPagedMileStones(int,int),它调用webapi方法并返回结果如上所述结构。我想将返回的响应从webapi强制转换为IPagedResponse。 But I am not able to make it work properly. 但我无法使其正常工作。 I have an Interface IPagedResponse and I want this function to return this information back to the component calling so that I can provide paging functionality. 我有一个接口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);
        }
    }

Wouldn't this work? 这不行吗? I don't see any variable on your code that is a type of IPagedResponse 我没有在您的代码中看到任何类型的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.

相关问题 可观察的Map函数未运行(Angular2,http) - Observable Map function not running (Angular2, http) Angular2-返回在map函数中创建的对象的可观察对象 - Angular2 - return observable of object created in map function 如何在Angular中从Http调用映射返回的Observable - How to map returned Observable from Http call in Angular Angular2:如何将 .map() 添加到 Observable API 对象? - Angular2: How to add .map() to Observable API object? 未调用http响应上的RxJs / Angular2映射函数 - RxJs/Angular2 map function on http response not called Angular2和RxJS:使用Map将另一个可观察到的响应替换为可观察到的响应 - Angular2 and RxJS : Replace Observable Response by another Observable Response using Map Angular2打字稿映射响应新类型 - Angular2 typescript map response to new type Angular2 Testing http服务说不支持地图功能 - Angular2 Testing http service saying map function not supported angular 2如何使用Observable分配JSON响应数组并在打字稿界面中映射并使用* ngFor在html中检索? - angular 2 how to assign an array of JSON response using Observable and map in typescript interface and retrieve in html using *ngFor? 如何在Angular 4中的http状态200响应的.map中引发可观察到的错误 - How to throw observable error in .map for a http status 200 response in Angular 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM