【问题标题】:Loading repeated master service at once一次加载重复的主服务
【发布时间】:2020-05-21 19:59:36
【问题描述】:

大部分组件都使用主数据列表。

我以前是这样在 ngInit 中加载的。

ngOnInit() {
    this.loadMasters();
 }

loadMasters() {
    this.masterService.getOrg().subscribe(response => {
      if (response && response['result']) {
        this.organisms = response['result'];
      }
    })

    this.masterService.getCat().subscribe(response => {
      if (response && response['result']) {
        this.category = response['result'];
      }
    })
......................
}

此代码已在大多数组件中重复。

我需要一个标准的解决方案

1) 避免在所有组件中调用这些主机,这会导致不必要的服务器调用。我更喜欢这个解决方案。 2)有没有办法缓存这个。如果上面没有解决办法就试试这个。

【问题讨论】:

  • 使用解析器创建一个父组件,您可以使用activatedRoute.snapshot.data获取所有子组件中的数据
  • 也可以使用组件继承,只取父基组件中的数据

标签: angular angular6 angular7 angular8


【解决方案1】:

在您的masterService 中,您可以创建两个 BehaviorSubject,例如:

categories$ = new BehaviorSubject<any>(null);
organizations$ = new BehaviorSubject<any>(null);

然后使用条件填充它们以避免多次调用。将 loadMasters 移动到服务内部,例如:

mastersService.ts

loadMasters() {
    // check for value in org before doing request
    if (!this.organizations$.value) {
         this.masterService.getOrg().subscribe(response => {
            if (response && response['result']) {
              // set value into behavior subject
              this.organizations$.next(response['result']);
            }
         })
    }

    // do the same for the categories
    if (!this.categories$.value) {
         this.masterService.getCat().subscribe(response => {
              if (response && response['result']) {
                  // set value into behavior subject
                  this.categories$.next(response['result']);
              }
         })
    }
...
}

然后在所有需要消费值的地方,都可以订阅行为主体,在此之前调用 loadMasters 确保数据已经加载:

mycomponent.ts:

public ngOnInit(): void {
    this.mastersService.loadMasters(); // load data if not loaded yet
    // consume the data from the behavior subjects
    this.mastersService.categories$.subscribe(value => {
       console.log(value);
    });
    this.mastersService.organizations$.subscribe(value => {
       console.log(value);
    });

}


【讨论】:

    【解决方案2】:
    const routes: Routes = [
      {
        path: 'master',
        component: MasterInfoComponent,
        resolve: {
          org: OrgResolverService,
          cat: CatResolverService,
        },
        children: [
        { 
            path: 'child1',
            component: child1Component,
        }
       ]
      },
    ];
    

    在所有子组件中,您可以获得这样的数据

    ngOnInit() {
       this.route.parent.data.subscribe(data => {
           this.cat= data.cat;
           this.org= data.org;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多