what I am trying to do here is making a store()
function in my front-end that creates a new question inside the database but I need to add the. active user id to that question's data before sending everything to the back-end.
this is the actual store()
function inside my questionsService
store(title : string, content: string, category_id : number): Observable<QuestionsInterface>{
let user_id : Observable<number>
user_id = this.authService.getUser()
.pipe(map(user => {
return user.id
}))
return this.http.post<QuestionsInterface>(this.baseUrl, {
title,
content,
user_id : user_id,
category_id
})
}
the this.authService.getUser()
returns an Observable that emits the actual user's data trough an interface
the problem here is that I cannot find out how should a treat the this.authService.getUser()
output to assign it to the user_id
variable`
do I need to subscribe to the output?
is there a way not to use subscribe? considering that is a single json response that is sent by the api
CodePudding user response:
I believe what you want to use is switchMap
. getUser
returns an Observable, switchMap
will take the emission from that observable and pass the return object from that and create another Observable to be listened to from it.
store(title : string, content: string, category_id : number): Observable<QuestionsInterface>{
return this.authService
.getUser()
.pipe(
take(1),
switchMap(user => this.http.post<QuestionsInterface>(
this.baseUrl,
{
title,
content,
user_id : user.id,
category_id
}));
}