I have this method:
onFormSubmit(formData: Pick<Habit, 'name' | 'repeatVal' | 'notification' | 'color' | 'question'>): void {
this.habitService
// tslint:disable-next-line:max-line-length
.createHabit(formData, this.authService.userId)
.pipe(first())
.subscribe((results) => console.log(results)
});
console.log(formData);
// I would like to use the id from my Observable here in this method
this.statusService.createStatuses(id);
this.updateService.callRefresh.next(true);
this.customizeForm.reset();
this.formDirective.resetForm();
// here the function to refresh the data-table should be called
this.updateService.callRefresh.next(false);
/*this.refresh.emit(null);*/
}
Unfortunately "results" gets logged as "undefined". This is my service with the method that makes a post request and returns an Observable:
createHabit(
formData: Partial<Habit>,
userId: Pick<User, 'id'>
): Observable<Habit> {
return this.http
.post<Habit>(
this.habitsUrl,
{ name: formData.name,
repeatVal: formData.repeatVal,
notification: formData.notification,
color: formData.color,
question: formData.question,
id: userId },
this.httpOptions
)
.pipe(
catchError(this.errorHandlerService.handleError<Habit>('createHabit'))
);
}
My service makes a post request to my database and there an automatic- autoincremented id gets created.
How can I access the id within my "onFormSubmit"-Method in order to use it in my "createStatuses" function?
This is my async-post-request-function:
exports.postHabit = async (req, res, next) => {
const errors = validationResult(req);
if(!errors.isEmpty()) return;
const name = req.body.name;
const repeatVal = req.body.repeatVal;
const notification = req.body.notification;
const color = req.body.color;
const question = req.body.question;
const id = req.body.id;
try {
const habitDetails = {
name: name,
repeatVal: repeatVal,
notification: notification,
color: color,
question: question,
id: id,
};
const result = await Habit.save(habitDetails);
res.status(201).json(result)
} catch (err) {
if(!err.statusCode){
err.statusCode = 500;
}
next(err)
}
};