I can't understand the order in which my code is executed. Here I provide 2 functions and output that is received:
component:
onSubmit(model) {
this.submitted = true;
let newUser: User;
newUser = this.usersService.addUser(this.model);
this.notifyParentOnAdd.emit(newUser);
console.log('saved Model as json ' + JSON.stringify(newUser));
}
service:
addUser(user: User) {
let savedModel: User = new User('','','',['']);
this.httpClient.post<User>('http://localhost:8080/user/create', user).
subscribe(res => {
console.log(res.id);
console.log(res.firstName);
console.log(res.lastName);
console.log(res.groups);
savedModel.id = res.id;
savedModel.firstName = res.firstName;
savedModel.lastName = res.lastName;
savedModel.groups = res.groups;
});
console.log('user-service: ' + savedModel);
console.log(JSON.stringify(savedModel));
return savedModel;
}
And the output is as follows:
users.service.ts:35 user-service: [object Object]
users.service.ts:36 {"firstName":"","lastName":"","email":"","groups":[""]}
user-form.component.ts:33 saved Model as json {"firstName":"","lastName":"","email":"","groups":[""]}
users.service.ts:26 7
users.service.ts:27 test
users.service.ts:28 test
users.service.ts:29 ["WORKERS"]
It clearly shows that subscribe()
method is executed at the very end that's why User
object is blank.
How to explain this behaviour?
How to force
subscribe()
to execute when service methodaddUser()
is invoked?