订阅行为主体,再次修改数据和设置值导致死循环

问题描述

我们有一个向导功能,其中我们有一个延迟加载的模块,它有一个父组件和多个子组件。

const routes: Routes = [
  {
    path : '',component :  WizardHomeComponent,canActivate: [HomeGuard],children : [
      {
        path : 'route1',component :  C1Component,canActivate: [ChildGuard]
      },{
        path : 'route2',component :  C2Component,{
        path : 'route3',component :  C3Component,canActivate: [ChildGuard]
      }
      {
        path : 'complete',component :  CompleteFlowComponent,canActivate: [ChildGuard]
      }
    ]
  }
];

HomeGuard 基本上是指服务,如果那里没有数据,则进行 API 调用,然后我们在服务中设置 BehavIoUr Subject 值并解析守卫。

HomeGuard

return new Observable(observer=> { 
  this.apiService.getAPIResult().subscribe(res=>{
    this.subjectService.setRequestData(res)  // Inside the subject service,setting the value for the behavIoUr subject
    observer.next(true)
  });
})

这是主题服务的代码

Subject Service 

private requestDataSource : BehaviorSubject<IWizard[]> = new BehaviorSubject<IWizard[]>(null);
public _requestData: Observable<IWizard[]> = this.requestDataSource.asObservable();

get requestData() {
  return this._requestData;
}

setRequestData(state) {
  this.requestDataSource.next(state);
}

现在,我们有了子路由保护,即 ChildGuard 。它基本上订阅了行为主体并检查条件,从而允许进入子组件。

ChildGuard

return this.subjectService.requestData
  .pipe(
    tap(wizard => {
      activeStep = wizard.filter(x=>x.isActive == true);
      /* Some othe logic for conditions */
    })
  )
  .pipe(
    map(wizard => isAllowed)
  )

现在,在我们的子路由组件中,每当用户遍历时,我都会更新 isActive 属性 & 用于检查的守卫内部。

问题是当用户点击浏览器后退按钮时,行为主题中没有设置值,并且不允许进入子组件。 为了尝试解决方案,在 WizardHomeComponent 内部,我订阅requestData observable 并尝试再次修改和设置主题,但这会进入无限循环。

WizardHomeComponent
this.subjectService.requestData.subscribe(res=>{
    /* Code to edit the res */
    const modifiedData = this.modificationFunction(res);
    this.subjectService.setRequestData(modifiedData)
});

解决方法

如果你想让它触发一次,你可以尝试这样的事情: 它只需要发出的第一个值。

WizardHomeComponent
this.subjectService.requestData.pipe(
  first(),// Only take the first value emitted
  map(res => this.modificationFunction(res)) /* Code to edit the res */
).subscribe(modifiedData =>
  this.subjectService.setRequestData(modifiedData)
);
,

你的结构有问题。我认为您的 URL 中应该有一个参数,并从后端获取数据并在服务中设置 requestData。不在组件中。

但通过简单的空检查(或其他任何检查!),您的问题将得到解决。

this.subjectService.requestData.subscribe(res=>{
    if(!this.checkValidation(res)) {
        /* Code to edit the res */
        const modifiedData = this.modificationFunction(res);
        this.subjectService.setRequestData(modifiedData)
    }
});

checkValidation(res){
//check if res is in modifiedData shape
}