使用 angular 2 & Typescript 从 url (web api) 获取 Json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41062895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:04:18  来源:igfitidea点击:

Get Json object from url (web api) with angular 2 & Typescript

angulartypescript

提问by amin89

`Hi, I need some help to get JSON data from web API on Visual Studio 2015 .net Core, Angular 2 & Typescript. Angular2 folders in /wwwroot/libs.

`嗨,我需要一些帮助才能从 Visual Studio 2015 .net Core、Angular 2 和 Typescript 上的 Web API 获取 JSON 数据。/wwwroot/libs 中的 Angular2 文件夹。

I'm using Angular 2's http.get(). The result of the get() function display an undefined value ... Why?

我正在使用 Angular 2 的 http.get()。get() 函数的结果显示一个未定义的值......为什么?

There's my files :

有我的文件:

Folders

文件夹

[API][2]

[API][2]

CustomersController.cs=> Access OK via http://localhost:45149/api/customers/=> [{...},{...},{...}]

CustomerController.cs=> 通过http://localhost:45149/api/customers/访问 OK=> [{...},{...},{...}]

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;
    }
}

customer.ts

客户.ts

export class Customer {
constructor(
    public Id: number,
    public Log: string,
    public Name: string
    ){}
}

customer.service.ts

客户服务.ts

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);
        });
}}

customer.component.ts

客户.component.ts

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

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

app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app/app.component.html' // => SPA
})

export class AppComponent {
title = "App-root"
}

Thank you.

谢谢你。

采纳答案by hagner

It looks like your server is set to serialize the response with camel-casing while you were trying to bind to properties with upper case names.

当您尝试绑定到具有大写名称的属性时,您的服务器似乎已设置为使用驼峰式外壳序列化响应。

If you wish to change your serializer settings to use another format, please check the following article: Web API serialize properties starting from lowercase letter.

如果您希望更改序列化程序设置以使用其他格式,请查看以下文章:Web API 序列化属性从小写字母开始

Otherwise you should be fine by binding to the lower case names on the angular side

否则你应该可以通过绑定到角度侧的小写名称