网站搜索

angular - 非相关组件的交互


在这里,我想将数据从通用过滤服务传递到页面摘要头部,我正在将数据传递给 release-decision-component.ts 文件中的 lastUpdatedTime。

筛选服务文件:

lastUpdatedTime : String;

release-decision-component.ts 文件:

this.releaseManagementService.getGlobalConfigParameters().subscribe((tableData: ParametersData) => {
    this.filterService.lastUpdatedTime = tableData.createdAt;
})

page-summary-header.html 文件:

<cds-page-title 
    type="primary" 
    [pageTitle]="pageTitle" 
    [subTitle]="subTitle">
</cds-page-title>

page-summary-header.ts 文件:

this.subTitle = `${'releaseManagement.lastUpdated'}:${this.filterService.lastUpdatedTime}`;

问题: 当用户第一次访问时,lastUpdatedTime 显示为 undefined。如果我再次访问,它会显示正确的 lastUpdatedTime。

答案#1

筛选服务文件:

使用 BehaviorSubject 跟踪 lastUpdatedTime。提供一个可观察对象 (lastUpdatedTime$) 来发出时间更新。

import { BehaviorSubject } from 'rxjs';

export class FilterService {
  private lastUpdatedTimeSubject = new BehaviorSubject<string>(null);
  lastUpdatedTime$ = this.lastUpdatedTimeSubject.asObservable();

  setLastUpdatedTime(time: string) {
    this.lastUpdatedTimeSubject.next(time);
  }
}

发布决策组件 (release-decision-component.ts)

 Fetches global config parameters.
    Sets lastUpdatedTime in FilterService.
    
this.releaseManagementService.getGlobalConfigParameters().subscribe((tableData: ParametersData) => {
        this.filterService.setLastUpdatedTime(tableData.createdAt);
      });

页面摘要头组件 (page-summary-header.ts)

Subscribes to lastUpdatedTime$ to update subTitle dynamically.

 this.filterService.lastUpdatedTime$.subscribe(lastUpdatedTime => {
      this.subTitle = `releaseManagement.lastUpdated: ${setDateFormatForTable(lastUpdatedTime)}`;
    });

HTML 模板 (page-summary-header.html)

Binds pageTitle and subTitle to the component's properties


 <cds-page-title 
      type="primary" 
      [pageTitle]="pageTitle" 
      [subTitle]="subTitle">
    </cds-page-title>