【问题标题】:How to Map Response object returned by Http Service to a TypeScript Objects using Observable Map function in Angular2如何使用Angular2中的Observable Map函数将Http服务返回的响应对象映射到TypeScript对象
【发布时间】:2017-03-13 20:50:59
【问题描述】:

您好,我创建了一个 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);
        }
    }

【问题讨论】:

    标签: angular typescript rxjs angular2-http


    【解决方案1】:

    这不行吗?我在您的代码中没有看到任何属于 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);
        }
    

    【讨论】:

    • 它是一个接口,代码出现在上面的问题中。导出接口 IPagedResponse { 总数:数量;数据:T[]; } 。我将再次发布完整的服务代码。是的,它奏效了。诀窍是在 Map 函数中返回一个返回 Response Object 的函数。
    【解决方案2】:
    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 1970-01-01
      • 2021-02-28
      • 2019-01-30
      • 2018-08-20
      • 2018-09-22
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      相关资源
      最近更新 更多