title: Return Observable from inside nested callbacks functions
body: <p>Good afternoon!</p>
  
  <p>I'm currently developing a web app in Angular2/4 and I have a problem with Observables. The goal is, inside a component, to call a function and when that function finishes, I want some code to be executed. So, the code in the <strong>"myComp.component.ts"</strong> file is:</p>
  
  <pre><code>this.myService.myFunc1().subscribe(() =&gt; {
      // this code has to be executed after myFunc1() finishes.
  });
  </code></pre>
  
  <p>The problem is inside the <em>"myFunc1()"</em> function of the <strong>"myService.service.ts"</strong> file. The structure of this function is the following:</p>
  
  <ol>
  <li>Define the function, which returns an <code>Observable&lt;Status&gt;</code>, where Status object is just <code>{ status: 'ok' }</code>. </li>
  <li>Call the function <em>"myFunc2()"</em> from another service, which returns an Observable, and do some staff.</li>
  <li>Call the function <em>"myFunc3()"</em> from another service, which returns an Observable and has to be executed after <em>"myFunc2()"</em> finishes.</li>
  <li>Call the function <em>"myFunc4()"</em> from another service, which returns an Observable and has to be executed after <em>"myFunc3()"</em> finishes.</li>
  <li>Return the <code>{ status: 'ok' }</code> into the <em>"myComp.component.ts"</em> in order the other code inside the subscribe() to be executed.</li>
  </ol>
  
  <p>So what I need is (3) nested calls of some functions, each and every one of them to be executed after the previous one. The most simple method is given below:</p>
  
  <pre><code>myFunc1(): Observable&lt;Status&gt; {
      // some code and then call of myFunc2()
      this.myService2.myFunc2().subscribe(data =&gt; {
         // do some staff here and then call of myFunc3()
         this.myService3.myFunc3().subscribe(data2 =&gt; {
            // do some other staff and then call of myFunc4()
            this.myService4.myFunc4().subscribe(data3 =&gt; {
               // do staff and then return program flow into the Component
               return Observable.of&lt;Status&gt;({status: 'ok'});
            });
         });
      });
  }
  </code></pre>
  
  <p>But of course the <code>return Observable.of&lt;Status&gt;({status: 'ok'});</code> doesn't work. I have been searching for a solution on the Internet and other Stackoverflow questions and I found suggestions like use of <em>flatMap()</em>, <em>mergeMap()</em>, <em>switchMap()</em> etc. I think that these solutions cannot be used in my case, because each function has to be executed after the other.</p>
  
  <p>What can I do? What I miss here? Thank you in advance for your help and your time! </p>