I'm currently diving into the world of observables and facing some challenges along the way.
Within my save()
function, I call initialize()
to retrieve certain Id's. In the initialize function, I am setting an Observable using a map method (payload
) which shows the correct values when logged to the console. I have attempted switching from map to subscribe without success.
TLDR; How can I properly assign a value to a pre-hoisted variable within a map/subscribe function?
Related question: What is the appropriate type of observable to use for serializing from an object?
save(post: Post, draftId?: number, postId?: number): Observable<any> {
let payload: Observable<any>;
if (!postId) {
post.state = post.state ? post.state : 'unsaved';
this.initialize(post)
.subscribe((res) => { //error here... cannot run
console.log('Waypoint: posts.service.ts:36');
payload = res;
});
} else if (draftId && postId) {
post.state = 'autosaved'
return this.updateDraft(post, draftId);
};
return payload;
}
initialize(post: Post): Observable<any> {
let resultPost: number;
let resultDraft: number;
var payload: Observable<any>;
this.createPost(post)
.subscribe(res => {
resultPost = res.id;
post.postId = res.id
this.createDraft(post)
.map(res => {
resultDraft = res.id;
let _payload = {
postId: resultPost,
draftId: resultDraft
};
console.log('Waypoint: posts.service.ts:62');
payload = Observable.create(_payload); // looks good!
}, (error) => { console.log(error) }).subscribe();
});
console.log(payload); //undefined :(
return payload;
}