问题
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.
回答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();
});
});
}
来源:https://stackoverflow.com/questions/47872897/angular-getting-authorization-token-asynchronously-before-http-calls