【发布时间】:2017-04-17 05:37:59
【问题描述】:
我正在开发一个进行 web api 调用的 Angular 2 应用程序。我目前正在使用 Visual Studio 2015、MVC5 webapi、typescript 和 Observables 从客户端脚本进行 web api 调用。看起来 web api 调用存在一些问题。我可以看到正在调用 webapi,但结果可能没有在需要时及时返回。请参阅下面的错误消息和我的代码
错误信息
[Route("api/customerorder")]
public class CustomerOrderController : ApiController
{
public IEnumerable<CustomerViewModel> GetCustomerOrder()
{
return new List<CustomerViewModel>
{
new CustomerViewModel { FirstName = "Jammy", LastName = "Oliver" , City = "London" , OrderCount = 12 },
new CustomerViewModel { FirstName = "Sam", LastName = "Walter" , City = "Birmingham" , OrderCount = 12 },
new CustomerViewModel { FirstName = "Tom", LastName = "Shanks" , City = "Liverpool" , OrderCount = 12 },
new CustomerViewModel { FirstName = "Dan", LastName = "Barack" , City = "Kent" , OrderCount = 12 },
new CustomerViewModel { FirstName = "Mike", LastName = "Jagger" , City = "Norwich" , OrderCount = 12 }
};
}
}
Customer.Service.ts
@Injectable()
export class CustomerService
{
constructor(private http: Http) { }
private customerOrderUrl = 'http://localhost:62440/api/customerorder';
getCustomerOrders(): Observable<CustomerOrder[]> {
return this.http.get(this.customerOrderUrl)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server Error'));
}
}
因此,如果您看到下面的代码,我正在尝试通过 loadCustomerOrder 方法调用 webapi,该方法反过来调用 Customer.Service.ts 中的服务调用。
Customer.Component.ts
import { Component, OnInit ,Input,OnChanges} from '@angular/core';
import { CustomerOrder } from './customerOrder';
import { CustomerService } from './customer.service';
import { GridModule, GridDataResult, PageChangeEvent, SortDescriptor, orderBy } from '@progress/kendo-angular-grid';
@Component({
moduleId: module.id,
selector: 'cust',
templateUrl: '/app/customers/customer.component.html',
providers: [CustomerService]
})
export class CustomerComponent implements OnInit {
private gridView: GridDataResult;
private sort: SortDescriptor[] = [];
private data: any[];
private pageSize: number = 10;
private skip: number = 0;
title = 'Customer List';
customerorder: CustomerOrder[];
ngOnInit(): void {
this.title = 'Customers';
}
constructor(private _custService: CustomerService)
{
this.data = [];
this.loadCustomerOrder();
}
loadCustomerOrder(): void {
this._custService.getCustomerOrders()
.subscribe(
CustomerOrder => this.customerorder = CustomerOrder,
err => console.log(err)
);
this.data = this.customerorder;
this.loadData();
}
private loadData(): void {
this.gridView = {
data: this.handleData(),
total: this.data.length
};
}
private handleData() {
var pagedData = this.data.slice(this.skip, this.skip + this.pageSize)
if (!this.sort) { return pagedData; }
var orderedAndPagedData = orderBy(pagedData, this.sort);
return orderedAndPagedData;
}
}
【问题讨论】:
标签: angular asp.net-mvc-5 asp.net-web-api2