0

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)
}
};
be2021
  • 29
  • 6
  • 1
    You can access the result in the subscribe (where you currently emit null). If you really need to access the id after that call, you'd have to make this whole thing use async/await, otherwise the stuff after the createHabit call will be executed before the subscribe block is actually hit (since a http request is async by itself). – Gunnar B. Apr 11 '21 at 15:02
  • Thank you for your answer, could you explain a bit further please, how I can access the result? I think what I am wanting to do comes somewhat close to this question https://stackoverflow.com/questions/49605090/how-to-return-value-inside-subscribe-angular-4 but I am still lost on how to do it. – be2021 Apr 11 '21 at 15:30
  • 2
    It depends a bit on what you want to do with it, but subscribe can have parameters (the content of the observable to be precise, you just left them out by putting `subscribe(() => ...`). E.g. you can do `subscribe((resultHabit) => ...` where `resultHabit` would be the returned object of the post request in this case. You could then do further stuff with this object in the subscribe. (You might want to move all the reset/refresh stuff in the subscribe too, that is more of a look and feel thing though.) – Gunnar B. Apr 11 '21 at 15:56
  • I have gotten as far as logging the result of the subscribe: .subscribe((results) => console.log(results)); , but it gets returned as undefined. I also changed my async-function of the backend to: const result = await Habit.save(habitDetails); res.status(201).json(result). I basically want to get the id that is created from the async-function to use it call another function in a different service. – be2021 Apr 11 '21 at 16:25
  • 1
    Not quite sure if that is what you meant with your last comment, but does the function you call via the post request actually return the value (or an object with that value) you need? `undefined` suggests that it is `void`. Otherwise, if you only need the id and `id: userId` is already the correct id, you could also just return that from `createHabit` (createHabit(...): Observable with a map operator in the pipe). – Gunnar B. Apr 11 '21 at 16:48
  • The id is not the "userId" that gets passed on. It's a different id that gets only automatically generated by my http-post-request. – be2021 Apr 11 '21 at 17:35
  • Basically my "onFormSubmit" function creates a habit that gets saved in my database and has a habitId which gets generated by the database automatically. I want to use that habitId to generate a data entry with it in a different table that has habitId as it's foreign key. – be2021 Apr 11 '21 at 17:47
  • Honestly that sounds like this should be handled in the backend entirely, but what does the function you call at `this.habitsUrl` return? That would have to be the id generated in the process. – Gunnar B. Apr 11 '21 at 17:53

0 Answers0