Angular2@Input和http.get
在将数据从一个组件传递到另一个组件时,我遗漏了一些东西。我使用@Input传递从http.get请求获得的数据。问题是,在请求尚未解析的情况下,尝试从传递的输入访问属性时,我遇到了一个错误Angular2@Input和http.get,input,components,angular,angular-http,Input,Components,Angular,Angular Http,在将数据从一个组件传递到另一个组件时,我遗漏了一些东西。我使用@Input传递从http.get请求获得的数据。问题是,在请求尚未解析的情况下,尝试从传递的输入访问属性时,我遇到了一个错误 //news.ts import {Component} from 'angular2/core'; import {Http, HTTP_PROVIDERS} from 'angular2/http'; import {Pagination} from './pagination'; @Component
//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}}似乎是可行的
有什么想法吗
谢谢有两种解决方案: 您可以在pagination.html中使用Elvis运算符
Page {{config?.total}}
这来自角度文档:
Elvis运算符(?)表示雇主字段是可选的,如果未定义,则应忽略表达式的其余部分
第二种解决方案是使用异步管道:
在这种情况下,您需要重写代码。构造函数中没有用
@Input()
修饰的变量。您必须等待Angular解析绑定,然后在以下步骤中访问它:
@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 in分页中抛出错误。ts注意,
async
管道不适用于对象:非常感谢,第一个解决方案适合现在的需要!我找不到有关此问题操作工具的任何内容…我相信OP是说config
来自HTTP请求,因此它甚至可能在ngOnInit()
中不可用。谢谢您的回答。正如MarkRajcok所说,它来自一个HTTP请求,我只是尝试了这个请求,但没有成功work@Choppy我假设它是在代码的其他地方定义的。在不知道如何获得config
的情况下,无法向您提供解决此问题的详细信息。Vlado建议的解决方案应该适用于像您这样的简单用例。请记住,输入变量在构造函数中不可用(;
//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);
});
}