简体   繁体   中英

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

@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.

The view is shown before the http response is returned.

{{webs?.name}}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM