`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.
I'm using Angular 2's http.get(). The result of the get() function display an undefined value ... Why?
There's my files :
[API][2]
CustomersController.cs => Access OK via 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;
}
}
customer.ts
export class Customer {
constructor(
public Id: number,
public Log: string,
public Name: string
){}
}
customer.service.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
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"
}
Thank you.