Angular 9 服务在登录后和页面重新加载后获取配置

Angular 9 Service to get configuration after login and after page reload

我在 Angular 方面不是很有经验,但仍在学习中。 我想做的是在 Angular 9 中编写一个服务,以便在成功登录后和页面重新加载时从应用程序配置(我有一个来自后端的端点)获取配置对象。我的服务:

import { Injectable } from '@angular/core';
import { OidcConfigurationClient, AppConfigurationDto } from './api-odm-manager.service';
import { Subject, Observable} from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class GetConfigurationService {

  private appConfig = AppConfigurationDto.fromJS({
    maxDaysForOrdersHistory: null
  });
  private subject = new Subject<AppConfigurationDto>();

  constructor(
    private readonly configService: OidcConfigurationClient
  ) { }

  public loadConfig() {
    this.configService.getDefaultOrderHistoryPeriod()
      .subscribe(config => {
        this.appConfig = config;
        this.subject.next(config);
      });
  }

  public getConfig(): Observable<AppConfigurationDto> {
    if (this.appConfig.maxDaysForOrdersHistory === null) {
      this.loadConfig();
    }
    return this.subject.asObservable();
  }
}

成功登录后,我调用了 loadConfig() 方法,但它没有正常工作。我的意思是它从端点获取配置,但在这种情况下 getConfig() 方法 returns this.subject.asObservable() 看起来它的行为不像我期望的那样。当我重新加载页面并转到需要此配置对象的组件时,它工作正常,因为 this.appConfig.maxDaysForOrdersHistory 为空,因此调用了 loadConfig。

在我需要配置对象的组件中:

  this.configurationService.getConfig().pipe(
      tap(days => {
          this.days = days.maxDaysForOrdersHistory;
          this.previousDate.setDate(this.date.getDate() - this.days);
          // some code that I need later
        })
      }))
      .subscribe(_ => {
          // this date is assigned earlier
          this.getOrdersHistory(this.previousDate, this.date);
      });

我很困惑,因为我对 Subject 还很陌生,你能告诉我如何正确地做到这一点吗?

我看到几个问题:

  1. 您return正在处理主题而不是数据。
  2. 如果您使用主题,则不需要 return 任何东西。引发事件,subject.next(yourdata) 更新服务本身的数据。
  3. 您需要将主题设置为 public 并让您的组件在事件引发时订阅它。

这就是我在我的应用程序中使用它的方式,希望对您有所帮助!

@Injectable()
export class DashboardService {

objDashboardData: DashboardData;
DashboardStatusChange: Subject<DashboardData> = new Subject<DashboardData>();

updateSummary() {
    this.getSummary(this.dateRange)
        .subscribe(data => {
            this.objDashboardData = data;
            this.DashboardStatusChange.next(this.objDashboardData);
        });
    }
}


// In your component you need to subscribe to subject event change to get the data you need
export class SidebarComponent implements OnInit {
objDashboardData: DashboardData;

ngOnInit() {
    this.dashboardService.DashboardStatusChange.subscribe(data => {
        this.objDashboardData = data;
    });
}