User 5842
User 5842

Reputation: 3029

Emit data using Observable between Shared Service and Component

Suppose I have a Service that I am sharing among a modal and a component. I want to do something like the following:

How can I, in my component, wait for the user to click on the continue button from the modal before continuing to making the request?

I was thinking of creating an Observable from the Shared service that could emit the data once I clicked on the continue button. My component would then subscribe to this Observable and on success, continue on with the network request.

Here is some code:

this.modalService.open('custom-modal');

// The following should only happen after entering values in the appropriate input fields and clicking on the continue button

this.sharedService.getFormFields.subscribe(values => {
    this.httpService.post(values[0], values[1]);
});

Is this the correct way of going about it? Any thoughts?

Upvotes: 0

Views: 280

Answers (1)

Alejandro Lora
Alejandro Lora

Reputation: 7802

I think that's an wrong way of approaching, at least sounds a bit over complicated to me.

My suggestion would be, you have a modal in the markup of the component. I would create an output event for when the user clicks the OK button in the pop up, and from there, I will emit an event that I will capture in the component. When I capture this, I will call my request with a normal service, receiving the values filled in through the same output event.

Sample:

Modal A:

@Output() clickEvt = new EventEmitter<MyModel>();

okButtonClicked(model: MyModel) {
   this.clickEvt.emit(model);
}

// This would be triggered once the click button has been pressed.

Component A: (markup)

<my-modal-component (clickEvt)="doRequest($event)"></...>

ComponentB: (ts)

doRequest(model: MyModel) {
   this.myNormalService.doRequest(model).subscriber()...
}

Upvotes: 1

Related Questions