Ionic2,Angular2,HTTP和Observable
问题描述:
阅读了几乎所有关于observables的信息后,我仍然不太清楚它们是如何工作的。Ionic2,Angular2,HTTP和Observable
我在这里做的http请求:
import { Component, OnInit, Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
webs: any;
getWebs(): any{
return this.http.get('here the url')
.map((res: Response) => res.json());
}
constructor(public navCtrl: NavController, private http: Http) {}
ngOnInit(){
this.getWebs().subscribe(response => {
this.webs = response;
console.log(this.webs);
});
}
}
在控制台上,this.webs正确打印。这意味着,获取请求工作正常,我正在检索我想要的对象。这是一个普通的JSON对象。
的问题是,在视图上,如果我尝试打印对象的某些属性(相同的属性我在控制台上看到)这样的
{{ webs.name }}
我得到的全部时间的错误:
Error in ./HomePage class HomePage - caused by: Cannot read property 'name' of undefined
这是与角1的sooo容易:(我已经读了很多教程,但我找不到任何回答我的问题。
感谢您的帮助。
答
在返回http响应之前显示视图。
{{webs?.name}}
应该工作。 或做this.webs=getWebs()
和{{webs.name | async}}
答
它应该是
this.getWebs().then((webs) => {
webs.subscribe(response => {
this.webs = response;
resolve(webs);
console.log(this.webs);
});
})
等你以后做getWebs是this.This未经测试的代码,但你的逻辑。 您在获取数据之前打电话。
ngOnInit(){
return new Promise(resolve => {
this.http.get('webs.json')
.map(res => res.json())
.subscribe(webs => {
this.webs = webs;
resolve(this.webs);
});
});
}
它的工作使用{{网?。名称}}和this.web = getWebs()非常感谢! – antsanchez