0

I am trying implement my http service component using below link

http://www.metaltoad.com/blog/angular-2-http-observables

My service component

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class DemoService {

  constructor(private http:Http) { }

  // Uses http.get() to load a single JSON file
  getFoods() {
    return this.http.get('http://ip.jsontest.com/').map((res:Response) => debugger; res.json(););
  }

  // Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
  // The entire operation will result in an error state if any single request fails.
  getBooksAndMovies() {
    return Observable.forkJoin(
      this.http.get('http://ip.jsontest.com/').map((res:Response) => res.json()),
      this.http.get('http://date.jsontest.com/').map((res:Response) => res.json())
    );
  }

}

And parent component

import {Component, ViewChild} from '@angular/core';
import {DemoService} from './demo.service';

@Component({
    selector: 'my-app', //<----the element defined in the index.html
    template: `
    <h1>Angular2, Hello {{name}}</h1>
    <div *ngIf="data_error">An error occurred while loading the data!</div>
    <div>{{foods?.ip}}</div>
    <div>{{books?.ip}}</div>
    <div>{{movies?.date}}</div>
    <br>
    `

})
export class AppComponent { 
    name: string;
    data_error: Boolean = false;
    public foods: any;
    public books: Array<string>;
    public movies: Array<string>;

    @ViewChild('mymodal')
    modal: ModalComponent;

    constructor(private _demoService: DemoService){
        this.name = "ANIL";
        this.getFoods();
        this.getBooksAndMovies();
    }

    close() {
        this.modal.close();
    }

    open() {
        this.modal.open();
    }

  getFoods() {
    this._demoService.getFoods().subscribe(
      (data:any[]) => { 
      debugger;
        //alert(data[0]); **this 'data' is undefined** :(
        this.foods = data


      },
      err => { this.data_error = true }
    );
  }

  getBooksAndMovies() {
    this._demoService.getBooksAndMovies().subscribe(
      data => {
        debugger;
        this.books = data[0];
        this.movies = data[1];
      }
    );
  } 

} // <--- we need to export the class AppComponent. 

Observable.forkJoin() can be subscribed successfully but could not understand what is the issue with http.get().map()

Please help!!!

3
  • What error are you getting with map()? Commented Jun 9, 2016 at 10:54
  • No errors in map(). I can see json object returned from the http call, but the issue is(as mentioned above) I could not get the same object inside subscribe(). Commented Jun 9, 2016 at 10:57
  • Yes, it is already working, see getBooksAndMovies(), but i want the similar case in getfoods() without Observables Commented Jun 9, 2016 at 11:00

1 Answer 1

1

In the map() method you have to return something, so you can't just do debugger; res.json();. Do instead this in your service:

// Uses http.get() to load a single JSON file
getFoods() {
    return this.http.get('http://ip.jsontest.com/').map((res:Response) => {
        debugger; 
        return res.json();
    });
}

[...].map((res) => res.json());

// is a shorthand for:

[...].map((res) => { return res.json(); });
Sign up to request clarification or add additional context in comments.

5 Comments

worked!!! :) I thought the 'return this.http....' would be returning something which could be subscribed then in parent! thanks for quick response!!! much appreciated! :))
Yes, that's right, but the .map() method allows you to manipulate the value you're subscribing to, hence you have to return something :) - The return in the .map() lambda function doesn't return in getFoods() but in the lambda function inside. Read more on lambdas here: piotrwalat.net/arrow-function-expressions-in-typescript
I tried going through the post you mentioned but could not get it :(, like if some function returns function then the parent can use it as function, if it returns an object parent can use the object(i just know this much)... at the moment it is not so important, but i would love to know the simple and short explanation :)
A lambda or "fat arrow" function is an inline function. Looking at the .map() method for instance - it takes a function as parameter and expects a return. So you could also write .map(processResponse) with a method in your class like processResponse(res: Response) { debugger; return res.json(); }. If you're writing .map((res) => res.json()); it implicitly returns res.json(), that's why you don't need an explicit return.
i got it 95%, but liked the way u explained it and your efforts, thanks :)

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.