Angular: поддерживать наблюдаемый в живых, пока не произойдет другое - PullRequest
0 голосов
/ 22 апреля 2020

У меня есть ModalComponent, который создается динамически через службу.
В этом компоненте я излучаю два события (onModalClose и onModalInputChanged), потому что в этом модале у меня есть форма, и каждый раз я измените значение, которое я выдаю.

проблема, с которой я здесь сталкиваюсь, заключается в том, что когда я подписываюсь на onModalInputChanged, я получаю первое значение, после которого наблюдатель каким-то образом закрывается, и я больше не получаю измененный значения

, так что я точно хочу, чтобы onModalInputChanged оставался в живых и продолжал получать измененные значения, пока я не отправлю событие onModalClose.
И это то, что я сделал до сих пор:
ModalComponent:

export class ModalComponent implements OnInit {

  @Output('onModalClose') onModalClose: EventEmitter<any> = new EventEmitter();
  @Output('onModalInputChanged') onModalInputChanged: EventEmitter<any> = new EventEmitter();

  inputChanged(value){// let 's say this is called when an input is changed
     this.onModalInputChanged.emit(value);
  }

  close(){ this.onModalClose.emit() }
}

Служба, которая создает этот компонент динамически:

@Injectable({
  providedIn: 'root'
})
export class ModalService {
private _container: ViewContainerRef;
  private component: ComponentRef<ModalComponent>;

  constructor(private _factoryResolver: ComponentFactoryResolver) { }

  setRootViewContainerRef(viewContainerRef) {
    this._container = viewContainerRef
  }

  openModal(): Observable<any>{
    const factory = this._factoryResolver.resolveComponentFactory(ModalComponent)
    this.component = factory.create(this._container.parentInjector)
    this._container.insert(this.component.hostView);
    // subscribe to on close event and remove the component's DOM from the document
    this.component.instance.onModalClose.subscribe(() => this.component.destroy());
    // here I receive the emitted value and returned it as observable so I can subscribe to it from another component
    return this.component.instance.onModalInputChanged.map(value => value).first();
  }
}

Теперь из любой другой компонент Я хочу откройте этот мод и подпишитесь на выданные значения, пока модал не закроется:

export class SomeComponent{

  constructor(private _modalService: ModalService){}

  openModalAndWaitForChanges(){
       this._modalService.openModal().subscribe(value => {
          console.log(value);// I get this value only the first time after that the observable does not emit any value
       });
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...