2017-03-28 92 views
0

我是新来的角2.我试图从角2asp.net核心Angular2 MVC HTTP GET问题

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

得到MVC控制器的数据,这是我的控制器

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 = "21" 
       }, 
       Address = new AddressViewModel() 
       { 
        Street1 = "asdf 9" 
       }, 
       TimeLine = TLVM 
      }; 
      return IVM; 
     } 
    } 
} 

我不能将数据从控制器绑定到angular2组件。当我尝试只显示内部控制台(console.log(this.IVM.ID))我得到一个错误不明身份,所以我认为这个问题是在订阅。有什么建议么?

回答

0

的get应该看起来更像是这样的:

getHeroes(): Observable<Hero[]> { 
    return this.http.get(this.heroesUrl) 
        .map(this.extractData) 
        .catch(this.handleError); 
} 

一个完整的示例,请参阅docs