antsanchez antsanchez - 9 months ago 64
TypeScript Question

Ionic2, Angular2, HTTP and Observables

After reading almost everything I found about observables, I still don't understand pretty well how they work.

I am doing the http request here:

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';

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) {}

this.getWebs().subscribe(response => {
this.webs = response;

On the console, this.webs is correctly printed. That means, the get request ist working fine and I am retrieving the object I want. That is a normal JSON object.

The problem is, on the view, if I try to print some property of the object (the same properties I see on the console) like that

{{ }}

I get the whole time that error:

Error in ./HomePage class HomePage - caused by: Cannot read property 'name' of undefined

That was sooo easy with Angular 1 :( I already read a lot of tutorials but I can't find any answer to my problem.

Thanks for your help.

Answer Source

The view is shown before the http response is returned.


should work. Or do this.web=getWebs() and {{ | async}}