【问题标题】:Angular 2 issue with web api callingWeb api调用的Angular 2问题
【发布时间】:2016-05-25 06:28:36
【问题描述】:

我正在实现 web api,它以这种格式返回数据。我认为当我尝试在客户端显示它时,有些事情是错误的。因为来自 RESTapi 的响应是 2d 的。请指导我哪里做错了,我将非常感激。

{
  "total": 134885,
  "data": [
    {
      "id": 21891,
      "source": "EventSystem",
      "logId": 4625,
      "level": "Information",
      "date": "2016-03-14T10:14:56",
      "category": "(0)"
    },
    {
      "id": 21892,
      "source": "MsiInstaller",
      "logId": 11728,
      "level": "Information",
      "date": "2016-04-29T12:13:24",
      "category": "(0)"
    },
    {
      "id": 21893,
      "source": "MsiInstaller",
      "logId": 1035,
      "level": "Information",
      "date": "2016-04-29T12:13:24",
      "category": "(0)"
    },
    {
      "id": 21894,
      "source": "MsiInstaller",
      "logId": 1042,
      "level": "Information",
      "date": "2016-04-29T12:13:24",
      "category": "(0)"
    },
    {
      "id": 21895,
      "source": "MsiInstaller",
      "logId": 1040,
      "level": "Information",
      "date": "2016-04-29T12:13:24",
      "category": "(0)"
    },
    {
      "id": 21896,
      "source": "Microsoft-Windows-RestartManager",
      "logId": 10001,
      "level": "Information",
      "date": "2016-04-29T12:13:24",
      "category": "(0)"
    },
    {
      "id": 21897,
      "source": "Microsoft-Windows-RestartManager",
      "logId": 10000,
      "level": "Information",
      "date": "2016-04-29T12:13:24",
      "category": "(0)"
    },
    {
      "id": 21898,
      "source": "MsiInstaller",
      "logId": 11728,
      "level": "Information",
      "date": "2016-04-29T12:13:33",
      "category": "(0)"
    },
    {
      "id": 21899,
      "source": "MsiInstaller",
      "logId": 1035,
      "level": "Information",
      "date": "2016-04-29T12:13:33",
      "category": "(0)"
    },
    {
      "id": 21900,
      "source": "MsiInstaller",
      "logId": 1042,
      "level": "Information",
      "date": "2016-04-29T12:13:33",
      "category": "(0)"
    }
  ]
}

但是当我试图在客户端显示记录时,它什么也没显示

api调用

import {Component, OnInit} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import {PaginatePipe, PaginationService, PaginationControlsCmp, IPaginationInstance} from 'ng2-pagination';
import {EventLogModel} from '../models/eventlogmodel';
import 'rxjs/Rx';

@Component({
    templateUrl: './appScripts/layout/eventlog.html',
    selector: 'eventlog',
    providers: [HTTP_PROVIDERS, PaginationService],
    directives: [PaginationControlsCmp],
    pipes: [PaginatePipe]
})

export class EventLogComponent implements OnInit {

    models: Array<EventLogModel> = [];
    private _page: number = 1;
    private _total: number;
    private _size: number = 10;
    constructor(private _http: Http) {

    }
    ngOnInit() {
        this.getPage(1);
    }
    getPage(page: number) {

        this._http.get("http://localhost:54363/api/data/" + page + "/" + this._size + "/")
            .map(res => (<Response>res).json())
            .map((models: Array<any>) => {
                let result: Array<EventLogModel> = [];
                if (models) {
                    models.forEach(model => {
                        result.push(
                            new EventLogModel(
                                model.id,
                                model.source,
                                model.level,
                                model.category,
                                new Date(model.date)
                            ));
                    });
                }
                    return result;
            }).
            subscribe(
            data => {
                this.models = data;
                console.log(this.models);
            },
            err => console.log(err)
            );
    }
}

html

<eventlog>
    <table class="table table-hover" id="myTable">
        <tr>
            <td class="col-md-3"><b>Level</b></td>
            <td class="col-md-3"><b>Date</b></td>
            <td class="col-md-3"><b>Source</b></td>
            <td class="col-md-3"><b>Id</b></td>
            <td class="col-md-3"><b>Category</b></td>
        </tr>

        <tr *ngFor="let model of models">
            <td class="col-md-3">{{model.level}}</td>
            <td class="col-md-3">{{model.date}}</td>
            <td class="col-md-3">{{model.source}}</td>
            <td class="col-md-3">{{model.id}}</td>
            <td class="col-md-3">{{model.category}}</td>
        </tr>
    </table>
    <pagination-controls (pageChange)="getPage($event)" id="server"></pagination-controls>

</eventlog>

【问题讨论】:

    标签: angular typescript asp.net-core-mvc


    【解决方案1】:

    问题在于请求的数据映射部分。根据您的 JSON 结构,您需要将数据迭代为 models.data.forEach 而不是 models.forEach

    .map((models: Array<any>) => {
        let result: Array<EventLogModel> = [];
        if (models.data) {
            models.data.forEach(model => {
                result.push(
                    new EventLogModel(
                        model.id,
                        model.source,
                        model.level,
                        model.category,
                        new Date(model.date)
                    ));
            });
        }
        return result;
    })
    

    【讨论】:

    • 我认为 models.data 是问题,但是当我尝试用它来实现它时,它显示任何类型的数据不存在的错误 []
    【解决方案2】:

    你没有提到问题是什么。我假设你得到一个错误,因为 modelnull

    尝试添加*ngIf

    <eventlog>
        <table *ngIf="model" class="table table-hover" id="myTable">
            <tr>
                <td class="col-md-3"><b>Level</b></td>
                <td class="col-md-3"><b>Date</b></td>
                <td class="col-md-3"><b>Source</b></td>
                <td class="col-md-3"><b>Id</b></td>
                <td class="col-md-3"><b>Category</b></td>
            </tr>
    
            <tr *ngFor="let model of models">
                <td class="col-md-3">{{model.level}}</td>
                <td class="col-md-3">{{model.date}}</td>
                <td class="col-md-3">{{model.source}}</td>
                <td class="col-md-3">{{model.id}}</td>
                <td class="col-md-3">{{model.category}}</td>
            </tr>
        </table>
        <pagination-controls (pageChange)="getPage($event)" id="server"></pagination-controls>
    
    </eventlog>
    

    或者使用安全导航操作符?

    <eventlog>
        <table class="table table-hover" id="myTable">
            <tr>
                <td class="col-md-3"><b>Level</b></td>
                <td class="col-md-3"><b>Date</b></td>
                <td class="col-md-3"><b>Source</b></td>
                <td class="col-md-3"><b>Id</b></td>
                <td class="col-md-3"><b>Category</b></td>
            </tr>
    
            <tr *ngFor="let model of models">
                <td class="col-md-3">{{model?.level}}</td>
                <td class="col-md-3">{{model?.date}}</td>
                <td class="col-md-3">{{model?.source}}</td>
                <td class="col-md-3">{{model?.id}}</td>
                <td class="col-md-3">{{model?.category}}</td>
            </tr>
        </table>
        <pagination-controls (pageChange)="getPage($event)" id="server"></pagination-controls>
    
    </eventlog>
    

    【讨论】:

    • 我使用了你给出的答案,但没有任何反应。
    • 很难说。你能创建一个允许复制的 Plunker 吗?
    【解决方案3】:

    这是我在代码中所做的一些更改,我的 api 运行良好。并且性能也得到了优化。

    Eventlog.components

    import {Component, OnInit} from 'angular2/core';
    import {Http, HTTP_PROVIDERS, Response} from 'angular2/http';
    import {Observable} from 'rxjs/Rx';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/do';
    import {PaginatePipe, PaginationService, PaginationControlsCmp, IPaginationInstance} from 'ng2-pagination';
    import {EventLogModel} from '../models/eventlogmodel';
    import 'rxjs/Rx';
    export interface PagedResponse<T> {
        total: number;
        data: T[];
    }
    
    export interface DataModel {
        id: number;
        data: string;
    }
    
    
    @Component({
        templateUrl: './appScripts/layout/eventlog.html',
        selector: 'eventlog',
        providers: [HTTP_PROVIDERS, PaginationService],
        directives: [PaginationControlsCmp],
        pipes: [PaginatePipe]
    })
    
    export class EventLogComponent implements OnInit {
    
        private _data: Observable<DataModel[]>;
        private _page: number = 1;
        private _total: number;
    
        constructor(private _http: Http) {
    
        }
        ngOnInit() {
            this.getPage(1);
        }
        getPage(page: number) {
            this._data = this._http.get("http://localhost:54363/api/data/" + page + "/10")
                .do((res: any) => {
                    this._total = res.json().total;
                    this._page = page;
                })
                .map((res: any) => res.json().data);
        }
    
    }
    

    html

    <eventlog>
        <div class="container">
            <table class="table table-striped table-hover" id="eventLogTable">
                <thead>
                    <tr>
                        <th class="col-md-3">ID</th>
                        <th class="col-md-3">Source</th>
                        <th class="col-md-3">Level</th>
                        <th class="col-md-3">Date</th>
                        <th class="col-md-3">Category</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let item of _data | async | paginate: { id: 'server', itemsPerPage: 10, currentPage: _page, totalItems: _total }">
                        <td class="col-md-3">{{item.id}}</td>
                        <td class="col-md-3">{{item.source}}</td>
                        <td class="col-md-3">{{item.level}}</td>
                        <td class="col-md-3">{{item.date}}</td>
                        <td class="col-md-3">{{item.category}}</td>
                    </tr>
                </tbody>
            </table>
            <pagination-controls (pageChange)="getPage($event)" id="server"></pagination-controls>
        </div>
    </eventlog>

    我的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      相关资源
      最近更新 更多