2

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

@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);
        });
    }
}

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

{{ webs.name }}

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.

2 Answers 2

6

The view is shown before the http response is returned.

{{webs?.name}}

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

Sign up to request clarification or add additional context in comments.

1 Comment

It's working using {{ webs?.name}} and this.web=getWebs() Thanks a lot!
2

It should be something

this.getWebs().then((webs) => {
   webs.subscribe(response => {
      this.webs = response;
       resolve(webs);
       console.log(this.webs);
   });
})

so after you getWebs do this.This is untested code but you get the logic. You are calling before you get data.

 ngOnInit(){
    return new Promise(resolve => {
       this.http.get('webs.json')
           .map(res => res.json())
             .subscribe(webs => {
                  this.webs = webs;
                  resolve(this.webs);
             });
           });
  } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.