![](/img/trans.png)
[英]Nested Observables behaving differently in Ionic2/Angular2 App
[英]Ionic2, Angular2, HTTP and Observables
在閱讀了我發現的關於可觀察物的幾乎所有內容之后,我仍然不太了解它們是如何工作的。
我在這里做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。 這意味着,get請求工作正常,我正在檢索我想要的對象。 這是一個普通的JSON對象。
問題是,在視圖上,如果我嘗試打印對象的某些屬性(我在控制台上看到的相同屬性),就像那樣
{{ webs.name }}
我得到了那個錯誤的全部時間:
Error in ./HomePage class HomePage - caused by: Cannot read property 'name' of undefined
使用Angular 1非常容易:(我已經閱讀了很多教程,但我找不到任何問題的答案。
謝謝你的幫助。
在返回http響應之前顯示視圖。
{{webs?.name}}
應該管用。 或者執行this.webs=getWebs()
和{{webs.name | async}}
{{webs.name | async}}
它應該是一些東西
this.getWebs().then((webs) => {
webs.subscribe(response => {
this.webs = response;
resolve(webs);
console.log(this.webs);
});
})
所以在你得到Webs之后這樣做。這是未經測試的代碼,但是你得到了邏輯。 在獲取數據之前,您正在打電話
ngOnInit(){
return new Promise(resolve => {
this.http.get('webs.json')
.map(res => res.json())
.subscribe(webs => {
this.webs = webs;
resolve(this.webs);
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.