【发布时间】:2017-10-18 23:57:51
【问题描述】:
我正在尝试从组件 A(模态窗口)中读取一个值,该值发生在从一组值中进行选择时。在组件 A 上按下 ok 按钮后,我希望将值传递给组件 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 没有更改的值。
任何意见将不胜感激
【问题讨论】:
标签: angularjs rxjs observable angular2-services subscription