嗨,我需要一些帮助来从Visual Studio 2015 .net Core,Angular 2和Typescript上的Web API获取JSON数据。/ wwwroot / libs中的Angular2文件夹。
我正在使用Angular 2的http.get()。get()函数的结果显示一个未定义的值...为什么?
有我的文件:
[API] [2]
CustomersController.cs =>通过http:// localhost:45149 / api / customers /访问确定= = [{...},{...},{...}]
public class CustomersController : Controller
{
// GET: api/customers
[HttpGet]
public IList<Customer> Get()
{
var objects = new List<Customer>
{
new Customer { Id = 1, Log = "user01", Name = "user1" },
new Customer { Id = 2, Log = "user02", Name = "user2" },
new Customer { Id = 3, Log = "user03", Name = "user3" }
};
return objects;
}
}
客户
export class Customer {
constructor(
public Id: number,
public Log: string,
public Name: string
){}
}
客户服务
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Customer } from "./customer";
import "rxjs/Rx"
@Injectable()
export class CustomerService {
private baseUrl = "http://localhost:45149/api/customers/"; // web api URL
constructor(private http: Http) { }
getCustomers() {
return this.http.get(this.baseUrl)
.map(res => <Customer[]> res.json())
.catch(error => {
console.log(error);
return Observable.throw(error);
});
}}
客户组件
import { Component, OnInit } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http';
import { Customer } from './customer';
import { CustomerService } from './customer.service'
@Component({
selector: 'app-api',
template: `
<ul class="">
<li *ngFor="let customer of customers">
<span class="">
{{customer.Id}} </span> {{customer.Name}}
</li>
</ul>`,
providers: [
HTTP_PROVIDERS,
CustomerService
] })
export class CustomerComponent implements OnInit{
api: string;
public customers: Customer[];
constructor(private customerService: CustomerService) {
this.api = "API Customers";
}
ngOnInit() {
this.customerService.getCustomers()
.subscribe(
customers =>
{
console.log(this.customers);
this.customers = customers;
},
error => alert("error"));
}}
app.module.ts
//
*** Imports ***
//
@NgModule({
imports: [BrowserModule, routing], //other modules the app depends on
providers: [CustomerService],
declarations: [AppComponent,
HomeComponent,UploadComponent,CustomerComponent],
bootstrap: [AppComponent] // root component to bootstarp
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app/app.component.html' // => SPA
})
export class AppComponent {
title = "App-root"
}
谢谢你。
您似乎在尝试绑定到具有大写名称的属性时,服务器已设置为使用驼峰式序列化响应。
如果您希望将序列化程序设置更改为使用其他格式,请检查以下文章:Web API序列化属性,从小写字母开始。
否则,您可以通过绑定到斜角的小写字母名称来解决问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句