0

before posting this i went to many other similar questions and not able to find solutions. like Angular 2 - Inject authorization token before each Http request

I am using AWS session which provides me Authorization token for makeing HTTP request. Now getting session can be asynchronous operation depending on need to refresh token.

Problem: I am not able to chain getting session and then making HTTP calls.

Versions Angular 5, RxJs 5.5.2

AuthService's get session function.

    getSession(): Observable<any> {
        const sessionOb = new Subject<CognitoUserSession>();
        // AysnFn4session is a callback implementation
        AysnFn4session((err, session) => { 
                console.log('Found Session');
                sessionOb.next(session);
                sessionOb.complete();
            });
        return sessionOb;
    }

API service's get function - Trail 1

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this._authService.getSession().switchMap((session) => {
      console.log('dasdasd');
      let token = '';
      if (session) {
        token = session.getIdToken().getJwtToken();
        options = options || {};
        options.headers = options.headers || new Headers();
        options.headers.append('Authorization', token);
      }
      return this._http.get(url, options);
    });
  }

API service's get function - Trail 2

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this._authService.getSession().pipe(mergeMap((session) => {
  console.log('So what??');
  let token = '';
  if (session) {
    token = session.getIdToken().getJwtToken();
    options = options || {};
    options.headers = options.headers || new Headers();
    options.headers.append('Authorization', token);
  }
  return this._http.get(url, options);
}));
}

Here how I am calling this api.

getItemInfo(item) {
return this._apiHttp.get('/assets/data/item.json')
  .map(res => {
    console.log(res);
    return res.json();
  })
  .subscribe(data => console.log(data),
     err => console.log(err), 
     () => console.log('done'));
}

Now the problem is in both the cases console just prints.and not http call is being made.

Found Session
done

I am not able understand where i am making mistake in using mergermap of switchmap in order to get the http request completed.

gaurang171
  • 9,032
  • 4
  • 28
  • 30
  • is this `cognitoUser.getSession()` the same as your `getSession` method? – LLai Dec 18 '17 at 17:02
  • @LLai cognitoUser.getSession is a method from AWS coginito identioty which uses callback function. Simplifying code in question to avoid confusion. – gaurang171 Dec 18 '17 at 17:13

1 Answers1

1

The error lies in getSession(). Your AsynFn4session callback is completing before the observer to the subject is listening. (An observer of a subject only receives values that are emitted after it has subscribed). This means the observer never receives the subject emit, so the observable sequence does not continue. I would use an observable instead of a subject

getSession(): Observable<any> {
    return new Observable(observer => {
        AsynFn4session((err, session) => {
            observer.next(session);
            observer.complete();
        });
    });
}
LLai
  • 13,128
  • 3
  • 41
  • 45
  • That works. Thank you for explanation. One more question. In what case subjects are good to use? I see most tasks can be achieved by using observable. – gaurang171 Dec 18 '17 at 19:18
  • 1
    @gaurang171 Subjects are typically used when you want to broadcast a change to multiple observers. For example, say I store my authenticated user in my authService. I can have multiple components subscribe to a subject from the authService. Now when that user changes his/her name, we can tell the subject to send out the change to all observers so they can react accordingly. So the big difference is observers of a subject share the same data source/stream, whereas observers of an observable get their own data source/stream. – LLai Dec 18 '17 at 19:39
  • 1
    thank you for explanation. I got better understanding now. :) – gaurang171 Dec 18 '17 at 21:58