2017-03-28 126 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