【问题标题】:Angular 2 - Service with BehaviorSubject creating a loopAngular 2 - 使用 BehaviorSubject 创建循环的服务
【发布时间】:2017-04-05 19:40:45
【问题描述】:

我有一个嵌套组件,其中包含一个可单击的图表,其中包含三个可选部分,这些部分将设置它所在的 md-tab-group 的 selectedIndex。我单击第一个,转到第一个选项卡,第二个导致第二个和第三个标签,非常简单。

问题是我正在使用的服务似乎正在创建某种循环。当我控制台服务正在采取的步骤时,我发现它每次都在变大。

相关服务代码:

  changeActiveTab(number) {
    console.log("Before: ");
    this._activeTab.subscribe(val => console.log(val));
    this._activeTab.next(number);
    console.log("After");
    this._activeTab.subscribe(val => console.log(val));
  } 

当我单击第一部分时,我看到了什么,导航回带有主导航的图表,然后再重复该过程两次:

Before:
0
1
After
1
Before:
1
2
2
2
After:
2
Before:
2
3
3
3
3
3
3
After
3

我对 BehaviorSubject 还很陌生,有什么想法会出错吗?

(我使用的示例来自here,如果有帮助的话)

父组件相关代码:

 selectedTab: number;
  subscription:Subscription;
  constructor( private _activeTabService: ActiveTabService) { }

  ngOnInit() {
    this.subscription = this._activeTabService.activeTab$.subscribe(
        selectedTab => this.selectedTab = selectedTab);
  }

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }

子组件的相关图表TS:

  onClick(event){
    if(event.series == 'Table'){
      this.changeActiveTab(1);
    }
    if(event.series == 'Chairs'){
      this.changeActiveTab(2);
    }        
    if(event.series == 'Desks'){
      this.changeActiveTab(3);
    }
  }

【问题讨论】:

    标签: javascript angular angular-services behaviorsubject


    【解决方案1】:

    你是对的。 changeActiveTab 确实会在每次通话时创建越来越多的订阅。 该服务不应进行订阅。 该服务应该有两种方法。 1. setTab - 将使用相关参数调用 subject.next。 2 注册 - 返回该主题的可观察对象。

    示例:

    export class tabService {
    subject  = new Subject(); 
    setTab(value: string)
       this.subject.next(value);
    }
    
    registerTab(){
    return this.subject.asObservable();
    }
    

    在我的组件中:

    myfunction(){
       this.tabService.registerTab().subscribe(
       (res) => do what you want with this value....
    );
    
    changeTab(value: string)
    {
       this.tabService.setTab(value);
    }
    

    【讨论】:

    • 感谢您的确认!你能解释一下这会是什么样子吗?如果我设置标签并返回它与我现在拥有的差不多吗?
    • 我加了一个简单的例子
    • 我在示例中使用 BehaviorSubject 而您在此处使用 Subject 是否重要?所以我的 onClick 函数看起来像:onClick(event){ this.tabService.registerTab().subscribe( (res) => { if(event.series == 'Table'){ this.changeActiveTab(1); } if(event.series == 'Chairs'){ this.changeActiveTab(2); } if(event.series == 'Desks'){ this.changeActiveTab(3); } } }
    • 我不确定您是否需要行为主题,但这取决于您,实现方式保持不变。
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2021-10-07
    • 2017-12-18
    相关资源
    最近更新 更多