0

I tried to write application based on tour of heroes. I have Spring application which shares resources and client app which should get this data. I know that resources get to client app, but I can't print it.

import { HeroesService } from './shared/HeroesService';
import { Observable } from 'rxjs/Observable';
import { Hero } from './shared/Hero';
import { OnInit } from '@angular/core';
import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: require('app/app.component.html!text')
})

export class AppComponent implements OnInit {
  errorMessage: string;
  items: Hero[];
  mode: string = 'Observable';
  firstItem: Hero;

constructor(private heroesService: HeroesService) { }

ngOnInit(): void {
    this.getHeroes();
    console.log(this.items);
    //this.firstItem = this.items[0];
  }

getHeroes() {
    this.heroesService.getHeroes()
              .subscribe(
                  heroes => this.items = heroes,
                  error => this.errorMessage = <any>error
                );
  }
}


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Hero } from './Hero';

@Injectable()
export class HeroesService {

    private heroesUrl = 'http://localhost:8091/heroes';

constructor(private http: Http) { }

getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    console.log(body);
    return body || { };
}

private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
}
}

In method extract data when I printed by console.log(body.data) I get undefined, but when I printed console.log(body) I get list of objects, therefore I return body instead body.data.

And when I print objects in extractData I get list of objects, but in AppComponent when I print console.log(this.items) I get undefined.

What's going on?

user
  • 4,410
  • 16
  • 57
  • 83
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Apr 19 '17 at 12:28

1 Answers1

0

this.getHeroes() returns an Observable which means that you can't get data out of it unless you subscribe to it. Think about it like a magazine subscription, by calling this.getHeroes(), you have registered for the magazine but you don't actually get the magazine until it gets delivered.

In order to get a console.log of the data that comes back in AppComponent, replace the .subscribe block with the following:

.subscribe(
  (heroes) =>{
    console.log(heroes);
    this.items = heroes;
  },
  error => this.errorMessage = <any>error
);

To further the magazine analogy, inside the subscribe block, you have received the magazine and here we are console logging its contents.

Hope this helps

derp
  • 2,300
  • 13
  • 20