我是Angular 2的新手。我正试图从角度2获取MVC控制器的数据
import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'subscriber',
templateUrl: './subscriber.component.html',
styleUrls: ['./subscriber.component.css']
})
export class SubscriberComponent {
public IVM: IncidentViewModel;
constructor(private http: Http) {
//this.IVM.ID = "ID";
this.http.get('api/Form/IncidentForm').subscribe(res => this.IVM = res.json() as IncidentViewModel); //map
console.log(this.IVM.ID)
}
}
interface IncidentViewModel {
ID: string;
Code: string;
DateTime: Date;
Address: Address;
Contact: ContactViewModel;
}
interface ContactViewModel {
FirstName: string;
LastName: string;
Telephone1: string;
Telephone2: string;
}
interface Address {
street1: string;
}
这是我的控制器
namespace Subscriber.Controllers
{
[Route("api/[controller]")]
public class FormController : Controller
{
[HttpGet("[action]")]
public IncidentViewModel IncidentForm()
{
List<TimeLineViewModel> TLVM = new List<TimeLineViewModel>();
TLVM.Add(new TimeLineViewModel()
{
Date = DateTime.Now,
Notes = "notes 1",
Title = "n1"
});
TLVM.Add(new TimeLineViewModel()
{
Date = DateTime.Now.AddHours(1),
Notes = "notes 2",
Title = "n2"
});
TLVM.Add(new TimeLineViewModel()
{
Date = DateTime.Now.AddHours(2),
Notes = "notes 3",
Title = "n3"
});
TLVM.Add(new TimeLineViewModel()
{
Date = DateTime.Now.AddHours(3),
Notes = "notes 4",
Title = "n4"
});
IncidentViewModel IVM = new IncidentViewModel()
{
ID = Guid.NewGuid(),
Code = "12345678",
Date = DateTime.Now,
Contact = new ContactViewModel()
{
FirstName = "kostas",
LastName = "kostas",
Telephone1 = "6974123456",
Telephone2 = "2101234567"
},
Address = new AddressViewModel()
{
Street1 = "asdf 9"
},
TimeLine = TLVM
};
return IVM;
}
}
}
我无法将数据从控制器绑定到angular2组件。当我尝试只显示内部控制台(console.log(this.IVM.ID))我得到一个错误未识别,所以我认为问题是在订阅内。有什么建议?
get应该看起来更像这样:
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
有关完整示例,请参阅docs。