我有一个服务返回数据模型。该模型包含 DateTime 属性 ( RelevantDateTime ) - 从服务器返回的当前 UTC DateTime。我想在与执行服务的组件不同的组件中使用这些数据。我正在使用 BahaviorSubject(我使用过Subject并将其更改为 BahaviorSubject)来执行此操作。它应该很简单,但不知何故我遗漏了一些东西 - 没有发出可观察的东西 - 需要数据的组件(HeaderComponent)没有得到它。查看我的代码:
export class MyService
{
content : any;
//I've changed the Subject to BahaviorSubject
timeOfExecutionSubject = new BahaviorSubject<Date>(new Date());
timeOfExecutionSubjectChanged : Observable<Date> = this.timeOfExecutionSubject.asObservable();
constructor (private httpClient : HttpClient){}
getData()
{
return this.httpClient.get<myModel>(<httpGetUrl>)
.pipe
.tap(
{
res => this.content = res;
this.timeOfExecutionSubject.next(content.RelevantDateTime);
}),
catchError(error => throwError(error))
);
}
getRelevantDateTime()
{
return this.timeOfExecutionSubjectChanged;
}
}
这是执行服务的组件:
export class MainComponent // This component execute the service
{
constaructor(private myService : MyService ){}
ngOnInit()
{
let sub = this.myService.getData().
subscribe (res =>
{
this.setData(res);
})
}
}
这是需要 RelevantDataTime 的组件
export class HeaderComponent implements OnInit
{
executionDateTime : string;
constructor(private myService: MyService)
{
this.myService.getRelevantDateTime().subscribe(
result => this.executionDateTime = moment(result).format("HH:mm");
)
}
}