0

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

const routes: Routes = [
  {
    path : '',
    component :  WizardHomeComponent,
    canActivate: [HomeGuard],
    children : [
      {
        path : 'route1',
        component :  C1Component,
        canActivate: [ChildGuard]
      },
      {
        path : 'route2',
        component :  C2Component,
        canActivate: [ChildGuard]
      },
      {
        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)
});
4

2 回答 2

0

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

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)
);
于 2021-02-09T13:51:34.203 回答
0

你的结构有问题。我认为您的 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
}
于 2021-02-09T14:01:30.977 回答