function updateProfile() {
let userToken;
const profileId = 1;
this.userService.getAccessToken()
.do(accessToken => userToken = accessToken)
.switchMap(accessToken => this.profleService.getContactIds(accessToken, profileId))
.flatMap(({account, address}) => this.profleService.updateprofile(userToken, this.profileInformation, account.id, address.id))
.subscribe(response => {
console.log(response);
// Perform actions with response data
}, error => {
// Handle the error here
});
}
Choosing to use flatMap
instead of a nested switchMap
has its advantages. In this context, switchMap
spreads the first observable that emits a value. By using flatMap
(also known as mergeMap
), we maintain the original behavior by processing all emitted values without nesting.
Although using flatMap
may not make a difference if only one value is emitted, the true power lies in its ability to handle multiple emitted values, preserving the observables' semantics while enhancing readability.
For those interested in the syntax of the projection function within flatMap
:
({account, address}) =>
this.profleService.updateprofile(userToken, this.profileInformation, account.id, address.id)
This syntax demonstrates ES2015 parameter destructuring, which simplifies extracting properties from parameters into local variables. Since account
and address
were consistently accessed, it is presumed that they are properties of the original res
. This technique is commonly used in callbacks and projection functions.
For instance:
interface Entity {
id: number;
}
declare const entities: Entity[];
function getById(entityId: number) {
return entities.find(({id}) => id === entityId);
}