angular - 如何使用 Angular2 中的 Observable Map 函数将 Http 服务返回的 Response 对象映射到 TypeScript 对象

标签 angular typescript rxjs angular2-http

您好,我已经创建了一个 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。但我无法使其正常工作。我有一个接口(interface) 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);
    }

关于angular - 如何使用 Angular2 中的 Observable Map 函数将 Http 服务返回的 Response 对象映射到 TypeScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40347814/

相关文章:

view - templateUrl 和 styleUrls 的 Angular2 相对路径?

typescript - 每个 http 请求的 Angular 2 加载器

typescript - 如何在 typescript 中取消回调 hell

Angular 2 Universal - 使用手写笔和哈巴狗模板进行服务器端渲染

angular - 未使用的表达式,需要赋值或函数调用 Promise 函数中的 Angular lint 错误

typescript 类无法访问对象的属性

typescript - 如何使用 TypeScript 解析 Vue.js 中的注入(inject)实例

RxJS:我如何 "manually"更新 Observable?

javascript - RxJS 不能与 Math.random() 配合使用

javascript - Rxjs 并行订阅者