仅在触发对.next的第二次调用后,才会触发Angular rxjs BehavioralSubject

问题描述

作为一种非常独特的方案的一部分,我在应用程序中使用了BehavioralSubject,但由于我希望它能正常工作,所以我无法正常工作。

场景:

在页面加载时,我从数据库中检索数据,其中包含我需要通过Map 填充到视图上的项目的集合。

一旦可观察对象完成,调用就会在bevavior主题上设置.next(T),但是,对该主题的订阅永远不会触发。

然后,用户与屏幕进行交互,调用数据服务上的.set(T)方法,然后启动behaviorsubject。当用户此时选择获取数据时,我原先希望触发的主题,开火。

结构:

当前方案包含以下组件:

1。)规划(.ts和.html) 2.)标签(.ts和.html) 3.)标签内容(.ts和.html)

  • 计划中包含一个引用,该引用又根据所选选项卡动态加载组件。

  • tab-content订阅dataservice.behavioral主题,称为资产$。

  • 选项卡内容有一个放置区域,可将新数据插入数据库,插入时,将触发对Assets $的订阅

根据当前情况,当/ planning加载时,我期望资产$ .subscribe(...)被触发,而不会。但是,当将项目放入选项卡内容中时,要插入数据,则按预期触发资产$ .subscribe(...),并且如果我通过/ planning上的刷新按钮再次加载,则与新页面加载相同,资产$ .subscribe(...)此时触发。

我只能推测,由于某种原因,dataservice中的行为主体直到该过程中的稍后一点才激活,例如当用户在页面加载后插入数据时。

对我来说,这种情况是完全正确的。我还尝试将更改检测策略更改为OnPush,希望它会强制更改而不会成功。

在此方案的各个工作部分下面的代码中:

<app-planning />

// .. this code is called OnInit as well as a button click
public fetch(): void {

  // .. initialization code before calling for data from the back-end
  // .. code left out for brevity

  forkJoin([this.shiftproxy.assets(),this.shiftproxy.planningplan(this.selectedshift['id'])])
    .subscribe(([assets,plan]: [AssetModel[],ShiftPlanModel]) => {

      // .. code left out for brevity

      this.shiftplanservice.updateplan(plan,assets); // inside update is a call to .next(...)
    });

  this.showtabsettings = true;
}

<app-tab-content />

ngOnInit(): void {
  // .. code left out for brevity

  // .. this.assetmap is just used to map the result from the Map<TKey,TValue> into something
  // .. the view needs
  this.assets$ = this.shiftplanservice.assets$.pipe(map(this.assetmap)); // subscribes to the subject
}

public itemDropped(event: CdkDragDrop<any[]>,area: string): void {
  copyArrayItem(event.previousContainer.data,event.container.data,event.previousIndex,event.currentIndex);

  // .. .set(...) also fires off .next(...),after this happens,everything works as expected
  this.shiftplanservice.set(this.tab.key,area,event.previousContainer.data[event.previousIndex]);
}

DataService:

public set(key: string,area: string,asset: AssetModel): void {

   // .. data is manipulated and added to a Map<TKey,TValue> called assets

   // .. next(...) is then called with the updated assets map
   // .. this works
   this.assets$.next(this.assets);
}

public updateplan(plan: any,assets: any): void {

  // .. based on the plan that comes back from the database
  // .. do we create a new Map<TKey,TValue> object and return that
  // .. as part of the BehaviorSubject

  // this only fires off after .set(...) has been called once,why?
  this.assets$.next(this.assets);
}

任何帮助,见识或替代方案将不胜感激,因为我不知道还有其他地方或其他地方。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)