1

In my ng2 service, i have a method that has 2 http.get calls. The function looks something like this:

getInfo(userId: number): any {

    this.http
       .get(apiUrl, options)
       .map(response => response.json())
       .subscribe(example => {
           this.example.FirstName = example.FirstName;
           this.example.LastName = example.LastName;

           this.http
               .get(`/api/${userId}`)
               .map(response => response.json())
               .subscribe(example => {
                   this.example.Street = example.Street;
                   this.example.City = example.City;

                   return this.example;
               });
       });
 }

The only problem is that, in my component, i can't subscribe to this function, because it's not of type Observable<Example>.

If I replace the type any for the function with Observable<Example> I get :

A function whose declared type is neither 'void' nor 'any' must return a value

But I do return a value, after the response.

How can I do this without having two separate functions?

Yes, i did checked this answer: https://stackoverflow.com/a/36712707/3264998

Community
  • 1
  • 1
Gerald Hughes
  • 5,771
  • 20
  • 73
  • 131

2 Answers2

3

Try writing this as your method body, this is one way there are other ways to solve this.

return this.http
   .get(apiUrl, options)
   .map(response => response.json())
   .flatMap(example => {
       this.example.FirstName = example.FirstName;
       this.example.LastName = example.LastName;

       return this.http
           .get(`/api/${userId}`)
           .map(response =>  {
               let example =response.json();
               this.example.Street = example.Street;
               this.example.City = example.City;

               return this.example;
           });
   });
Deepak Sharma
  • 1,873
  • 10
  • 23
1

My solution using rxjs/Rx flatMap :

import {Observable} from 'rxjs/Rx';


ngOnInit() {
  const usersId = ['USR001', 'USR003'];
  this.doRequest(usersId);
}

doRequest(queryArr, previousObservable = null) {
        if (queryArr.length) {
            const url = 'api/' + queryArr.shift();
            let observable = null;
            if (previousObservable) {
                observable = previousObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.doRequest(queryArr, observable);
        } else {
            return previousObservable;
        }
    }
abahet
  • 10,355
  • 4
  • 32
  • 23