0

I have the following piece of code:

var roomStatementToBeCreated = new RoomStatement();
var roomId = this.bookingRequest.roomDetails.allocations[0].roomId;
this.roomService.get(roomId).then((room) => {
    roomStatementToBeCreated.buildingId = +room.building.id_original;
    roomStatementToBeCreated.roomTypeId = +room.roomType.id_original;
    roomStatementToBeCreated.roomNumber = +room.id_original;
}); 

In the .then() all the variables get their values. However after that it has to get saved in the DB and it is saved with 0 values. And when debugging it says that after leaving the .then() they have undefined values.

I supposed this issue has to do with scope, however I'm not sure how the roomStatementToBeCreated.buildingId and others can save their values outside of the .then().

  • 1
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Aug 10 '20 at 12:29
  • I understand why it is happening, however I need a quick fix for it since I'm not sure how to do it so that it saves the values. – Valeri Vladimirov Aug 10 '20 at 12:35
  • 2
    There are several answers on that question, with the first three having explanations of how to "fix" the "problem". The key here is that any code that uses the information retrieved from the service must be called from within the `then` function, or after an `await` statement within an `async` function. – Heretic Monkey Aug 10 '20 at 12:44

0 Answers0