Angular2 - 从WebAPI映射数据时出错(错误:尝试差异时出错)

时间:2017-07-25 06:54:21

标签: c# angular asp.net-web-api

我一直在尝试各种从API获取数据并使用ngFor在列表中显示它。我已经尝试了承诺,可观察并玩了地图,订阅,异步管道,但没有运气。我确定API已被点击但由于某种原因,它要么显示空白数据,要么抛出不同的错误。我最近得到的是

  

尝试diff'[{“id”:1,“name”:“Bike 1”},{“id”:2,“name”:“Bike”时出错   2“},{”id“:3,”name“:”Bike 3“}]'       在DefaultIterableDiffer.diff ..

我预感到该函数没有返回ngFor期望的数组。

以下是我的 add-bike.component.ts

import { Component, OnInit } from '@angular/core';
import { Bike } from "./Entity/bike";
import { BikeService } from "./bike.service";
@Component({
    selector: 'add-bike',
    template : `<p>Hello</p><ul>
            <li *ngFor="let bike of bikes">
                {{ bike.name}}
            </li>            
        </ul>`
})

export class AddBikeComponent implements OnInit {

    bikes: Bike[] = [];
    errorMessage: string;
    constructor(private bikeService: BikeService) {

    }

    ngOnInit(): void {
        this.bikeService.getRequest().subscribe(res => this.bikes = res);
    }
}

bike.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { Bike } from './Entity/bike';

@Injectable()
export class BikeService {
    private _url = 'api/bikes'; 
    constructor(private http: Http) { }
    getRequest() {
        return this.http.get(this._url).map(res => res.json());
    }

}

bike.ts

export class Bike {
    id: number;
    name: string;
}

C#中的Web API代码:

public class Bike
    {
        public int id { get; set; }
        public string name { get; set; }
    }

public IHttpActionResult Get()
        {
            List<Bike> list = new List<Bike>();
            list.Add(new Bike() { id = 1, name = "Bike 1" });
            list.Add(new Bike() { id = 2, name = "Bike 2" });
            list.Add(new Bike() { id = 3, name = "Bike 3" });
            return Ok(JsonConvert.SerializeObject(list));
        }

Api回复:api / bikes

"[{\"id\":1,\"name\":\"Bike 1\"},{\"id\":2,\"name\":\"Bike 2\"},{\"id\":3,\"name\":\"Bike 3\"}]"

3 个答案:

答案 0 :(得分:1)

您从回复中获得的内容是您当前需要解析为JSON的格式,您可以通过添加第二张地图来实现:

getRequest() {
    return this.http.get(this._url)
      .map(res => res.json())
      .map(res => JSON.parse(res))
}

DEMO:http://plnkr.co/edit/onfdvVmoCO3DVqgXn9cz?p=preview

答案 1 :(得分:1)

bike.service.ts

getRequest() {
        return this.http.get(this._url).map(res => res.json() as  Bike[]);
    }

确保自行车实体

export class Bike {
    id: number;
    name: string;
}

答案 2 :(得分:1)

如果WebApi返回类类型,则不必使用JsonConvert.SerializeObject

我没有和你的其他代码一起尝试这个,但是可能会改变你的返回方法可能会有效;

return Ok(list);