Here is an example for a login function that first gets a accessToken from facebook, then sends that token to a second service to get the user profile.
login(): Observable<any> {
let fas: FacebookAuthResponse = {
accessToken: null,
expiresIn: null,
signedRequest: null,
userID: null,
};
let fbResponse: Subject<any> = new Subject();
let userProfile: Subject<any> = new Subject();
this.fb.login().then((response: FacebookLoginResponse) => {
fbResponse.next(response.authResponse);
}), (error: any) => {
console.error(error);
};
fbResponse
.map((far: FacebookAuthResponse) => far.accessToken)
.mergeMap(accessToken => this.processLogin(accessToken))
.subscribe(res => userProfile.next(res));
return userProfile
}
processLogin(token){
let headers = new Headers({ 'Authorization': 'Bearer facebook ' + token });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:8000/user-profile/', options)
}
Here I use rxjs Observable and rxjs Subject. I would recommend reading this article: http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/
fbResponse.next(response.authResponse);
When this.fb.login is resolved, call next on the fbResponse Subject to further process the fb.login response.
.map((far: FacebookAuthResponse) => far.accessToken)
here map is used to get the accessToken from the fbLogin response.
What happens next is not part of your question, but might be interesting.
.mergeMap(accessToken => this.processLogin(accessToken))
.subscribe(res => userProfile.next(res));
mergeMap let's us subsribe to the last call in the request chain, and return that value.
So when we subscribe to this login request, the user profile from the last call is returned when all request are completed synchronously.