2016-02-13 96 views
1

我從組件傳遞數據到另一個組件時缺少一些東西。我使用@Input傳遞數據,這是從http.get請求獲得的。問題是,當請求尚未解析時,我試圖從傳入的輸入中訪問屬性時出現錯誤。Angular2 @Input和http.get

//news.ts 
import {Component} from 'angular2/core'; 
import {Http, HTTP_PROVIDERS} from 'angular2/http'; 
import {Pagination} from './pagination'; 

@Component({ 
    selector: 'news', 
    templateUrl: 'app/news.html', 
    viewProviders: [HTTP_PROVIDERS], 
    directives: [Pagination] 
}) 
export class News { 

    news = []; 

    pagination: Pagination; 

    constructor(http: Http) { 
     http.get('http://test.com/data') 
      .map(res => res.json()) 
      .subscribe(news => this.news = news); 
    } 
} 

//pagination.ts 
import {Component, Input} from 'angular2/core'; 

@Component({ 
    selector: 'pagination', 
    templateUrl: 'app/pagination.html' 
}) 
export class Pagination { 
    // page: int = 1; 

    @Input() config; 

    constructor() { 
     // this.page = this.config.number; 
    } 
} 

//Pagination.html 
Page {{config.total}} 

config.total在加載時產生錯誤。但是儘管{{config}}似乎能夠工作。

任何想法?

感謝

回答

1

有兩種方案來解決這個:

您可以在pagination.html使用Elvis操作符

Page {{config?.total}} 

這是從角文檔:

貓王運算符(?)表示僱主字段是可選的,如果未定義,則應忽略表達式的其餘部分。

第二種解決方案是使用異步管: https://angular.io/docs/ts/latest/api/common/AsyncPipe-class.html

在這種情況下,你需要重寫代碼。

+0

注意'async'管不能用於對象:http://stackoverflow.com/a/34561532/215945 –

+0

非常感謝,第一個解決方案適合現在的需要!我找不到任何這個問題instellement ... – Choppy

+0

好...我的標記答案正確:) –

0

@Input()裝飾的變量在構造函數中不可用。你必須等待,直到角度解析綁定和稍後訪問它component's lifecycle

ngOnInit() { 
    this.page = this.config.number; 
} 
+0

我相信OP是說''config'來自一個HTTP請求,所以它可能甚至不可用'ngOnInit()'。 –

+0

感謝您的回答。正如Mark Rajcok所說,它來自一個HTTP請求,我只是試過這個,它不起作用 – Choppy

+0

@Choppy我認爲它是在代碼的其他地方定義的。無法告訴你更多的細節如何解決這個問題,而不知道你如何獲得'config'。解決方案Vlado建議應該爲您的簡單用例工作。請記住,輸入變量在構造函數中不可用(; – Sasxa

0

@Vlado Tesanovic我只是想第二個解決方案,因爲我可能需要處理在構造函數中的數據。 我做了什麼:

//news.ts 
    constructor(http: Http) { 
     // http.get('http://lechiffonbleu.com:1337/news/test') 
     // .map(res => res.json()) 
     // .subscribe(news => this.news = news); 

     this.news = new Promise((resolve, reject) => { 
      resolve = http.get('http://lechiffonbleu.com:1337/news/test') 
       .map(res => res.json()) 
       .subscribe(news => this.news = news); 

      console.log(this.news); 
      console.log(resolve); 
     }); 
    } 

嗯,我無法弄清楚如何正確解決的承諾,因此不會引發錯誤的@input在pagination.ts