2016-02-13 100 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