6

I wish to create a function that returns an Observable<any> but before returning another asyncronous task must complete (an Observable<string>), in order for a value to be passed to the returned Observable.

 @Injectable()
 export class MyComponent
 {

      GetAuthToken = function() : Observable<string>
      {
           return this._storageService.GetAsString('authToken');
      }

      GetData = function(authToken) : Observable<any>
      {

           let headers = new Headers();
           headers.append('authToken', authToken);
           var getUsers = this._http.get('/api/endpoint', { headers: headers })
                 .map((resonse: Response) => resonse.json()));

           return getUsers;        
      }


      DoIt = function() : Observable<any>
      {
          this.GetAuthToken ().Subsribe(t=> {
              return GetData(t); 
          })
      }          


 }

So instead of passing the authToken parameter into the GetData function, I wish to execute the GetAuthToken function within the GetData function, wait for its completion, and then still return the http observable.

Executing the DoIt function would return the subscriber, not the GetData Observable

5
  • 2
    Completely unrelated question: Why are you using syntax: GetAuthToken = function() {...} and not GetAuthToken() {...} like everyone else (I know these two method definitions aren't the same though)? Commented Nov 7, 2016 at 15:06
  • 1
    Use Observable.forkJoin, check this: github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/… Commented Nov 7, 2016 at 15:06
  • @Martin stackoverflow.com/questions/336859/… Commented Nov 7, 2016 at 15:08
  • @camaron the first observable needs to finish executing before the second begins. And I need to return the Observable<Response> from the Http service, not an amalgamation Commented Nov 7, 2016 at 15:09
  • @gunwin I understand the difference but I really doubt you need to use it. This btw makes extending your class very complicated. It's basically the same problem as described here stackoverflow.com/questions/40398381/… Commented Nov 7, 2016 at 15:12

2 Answers 2

10

Try using concatMap():

DoIt() : Observable<any>
{
    return this.GetAuthToken()
        .concatMap(token => this.GetData(token)); 
}   
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. This works. My WebAPI service wasn't running, which caused my null problem. Thank you!
similar problem - concatMap() works perfect ! Thank you.
0

This is also possible using flatMap

DoIt() : Observable<any>
{
    return this.GetAuthToken()
        .flatMap(token => this.GetData(token)); 
}   

Comments

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.