oauth2 API calls and refreshing tokens (chaining observables?)

For the benefit of anyone else going through this, here’s what I ended up with (based on the SO topic linked above).

Page.ts – now nice and clean and straight forward

this.WAC.call(method, params)
	.subscribe(
		response => {
			// DO STUFF
		},
		err => {
			// ERROR
		}
	);

WAC.ts (API Client)

refreshToken() {
	...
	// call to get a new access token
	return this.http.post(this.API_ENDPOINT + '/token.php', body, options);
}

call(method, params) {
	// check if access_token is expired, if so use refresh token to get a new one
	let now = Date.now() / 1000;
	if (this.authData.access_expires < now) {
		return this.refreshToken().flatMap(res => {
			let res_json = res.json();
			this.setAuthData(res_json);
			return this.call(method, params);
		});
	} else {
		...
		// make the API call
		return this.http.post(this.API_ENDPOINT + '/resource.php', body, options)
			.map(res => res.json());
	}
}

It seems like the flatMap() vs map() was the key – here’s another couple references about the topic:


Thanks again!
Brian