我正在尝试读取组件A(模态窗口)中的值,该值在从一组值中进行选择时发生。在组件A上按下确定按钮后,我希望将值传递给组件B(页面组件)。我有一个服务,并按照此处指定的示例Delegation: EventEmitter or Observable in Angular2
我看到主题在.next()上更新。但是从我的订阅者,当我尝试从组件B访问它时,我没有看到更新的值。
请帮我查一下究竟是什么问题,
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);
}
}
组件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是按钮的事件处理程序,模式(组件A打开)用户选择一个值,然后组件B(页面)需要处理该值。
在组件B中,我确实将订阅放在onINit()中,但是this.test没有更改的值。
非常感谢任何输入
答案 0 :(得分:0)
我认为问题在于你有XService的两个实例,一个用于组件A,一个用于组件B,因为你在组件的provider属性上设置了它。你应该做一个moudle包装这两个组件并在那里设置XService的提供者。有了它,只有一个XService实例与这两个组件共享。
模块应该是这样的:
@NgModule({
imports: [],
declarations: [
ComponentA,
ComponentB
],
entryComponents: [
ComponentA,
ComponentB
],
providers: [XService],
exports: []
}
)export class MyModule {}
希望得到这个帮助。