【问题标题】:Observable/Subscription in Angular 2 service for passing data between 2 componentsAngular 2 服务中的 Observable/Subscription 用于在 2 个组件之间传递数据
【发布时间】: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


    【解决方案1】:

    我认为问题在于您有 两个 XService 实例,一个用于组件 A,一个用于组件 B,因为您是在组件的 provider 属性上设置的。您应该做一个封装这两个组件的模块,并将 XService 设置为提供者。这样,两个组件将只共享一个 XService 实例。

    模块应该是这样的:

    @NgModule({
    imports:         [],
    declarations:    [
        ComponentA,
        ComponentB
    ],
    entryComponents: [
        ComponentA,
        ComponentB
    ],
    providers:       [XService],
    exports:         []
    }
    )export class MyModule {}
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2018-02-22
      • 1970-01-01
      • 2017-09-21
      • 2016-03-24
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      相关资源
      最近更新 更多