I am trying to read a value from a Component A( Modal window) which happens on selection from a set of values. Once the ok button is pressed on Component A, I want the value to be passed to Component B ( Page component). I have a service for this and followed the example specified here Delegation: EventEmitter or Observable in Angular2
I see that the subject updates on .next(). But from my subscriber , i don't see the updated value when i am trying to access it from Component B.
Please help me find what exactly is the issue here ,
XService.ts
import { Injectable } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Observable } from 'rxjs';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class XService {
constructor(private modalService: NgbModal) {}
// Observable Item source
public _adModalSelectedSource = new BehaviorSubject<string>('w');
// Observable Item stream
selectedRow$ = this._adModalSelectedSource.asObservable();
// service command
changeNav(string) {
this._adModalSelectedSource.next(string);
}
}
Component A.ts
btnClick(btn) {
if (btn.id === 'ok') {
this.XService.changeNav('yes');
this.activeModal.close(this.selectedRows);
} else {
this.activeModal.dismiss();
}
}
ComponentB.ts
import { Component, ViewChild} from '@angular/core';
import { NgbDropdownConfig, NgbTabset } from '@ng-bootstrap/ng-bootstrap';
import { Subscription} from 'rxjs/Subscription';
import { XService} from '../../x/x.service';
import { ActivatedRoute, Params } from '@angular/router';
@Component ({
selector: 'compb',
templateUrl: './compb.html',
styleUrls: ['./compb.component.scss'],
providers: [xService, NgbTabset]
})
export class ComponentB {
xService: XService;
test: any;
subscription:Subscription;
route: any;
tabs: any;
subTabs: { all: 'all', problemMachines : 'problem_machines' };
constructor( X:XService, tabs: NgbTabset, route: ActivatedRoute) {
this.xModalService = X;
this.route = route;
this.tabs = tabs;
this.subTabs = { all: 'all', problemMachines : 'problem_machines' };
}
SelectHandler(data) {
if (data.item.id === 'XXX') {
this.XService.openModal().then(() => {
**console.log('test value'+ this.test);**
console.log('close');
//this._loadData();
});
}
}
ngOnInit() {
this.filterText = '';
this.subscription = this.xService.selectedRow$.subscribe(test => this.test = test);
}
ngOnDestroy() {
//on destroy hook
this.subscription.unsubscribe();
}
}
SelectHandler is the event handler for button on which the modal( Component A opens) user picks a value which then needs to be available for Component B( page) to process on.
In Component B I do put the subscription in onINit() , but this.test does not have the changed value.
Any inputs will be greatly appreciated