0

I'm struggling with passing json from service layer to component and then invoking functions sequentially. Here is what I've already accomplished:

users.service.ts

addUser(user: User) {
    return this.http.post('http://localhost:8080/user/create', user).map(res => res.json());
  }

And then component layer:

async onSubmit(model) {
await new Promise(resolve => {
  setTimeout(() => {
    this.submitted = true;
    this.usersService.addUser(model).subscribe(data => this.savedModel = data);
    resolve();
  }, 500);
});
this.sendNotification();
}

@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit(JSON.stringify(this.savedModel));
}

savedModel is undefined. How can I fix this/what am I doing wrong?

EDIT: Top of the component is:

@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {

groups: Group[];
model: User;
savedModel;
2
  • Have you declared savedModel in the component? Commented Dec 8, 2017 at 23:12
  • how does your parent component look like, (child tag and TS code related to this) Commented Dec 10, 2017 at 9:34

1 Answer 1

1

It seems like addUser may be taking longer than 500 seconds, but rather than create an artificial timer you can emit when user service completes.

onSubmit(modal) {
  this.usersService.addUser(model).subscribe(data => {
    this.savedModel = data;
    this.sendNotification(); // or just .emit here
  });
}

You also don't need to wrap this in a Promise or anything.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't get it. I did as you suggest and still it's undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.