这可行,但是我不想使用null作为startDate和endDate的初始值,我需要使用另一个可观察的userInfo $的值进行初始化,如下所示:
export interface IUserInfo {
UserEntryStartDate: Date;
UserEntryEndDate: Date;
// ...
}
public userInfo$: Observable<IUserInfo>;
private dateFilterSubject = new Subject<{
startDate: Date;
endDate: Date;
}>();
this.userInfo$
.pipe(
withLatestFrom(
this.dateFilterSubject.pipe(
startWith({
startDate: null,
endDate: null
})
)
)
)
.subscribe(([userInfo, dateFilters]) => {
// ... do stuff
}
这就是我想要做的
this.userInfo$
.pipe(
takeWhile(() => this.active),
withLatestFrom(user => // userInfo from outer observable
this.dateFilterSubject.pipe(
startWith({
startDate: user.UserEntryStartDate,
endDate: user.UserEntryEndDate
})
)
)
)
.subscribe(([userInfo, dateFilters]) => {
// do stuff
}
它甚至可以提供正确的自动填充功能并在user
参数上键入,
但是在订阅时出现错误:
Type 'Observable<{ startDate: Date; endDate: Date; } | { startDate: Date; endDate: Date; }>' must have a '[Symbol.iterator]()' method that returns an iterator.
我在做什么错了?
答案 0 :(得分:1)
您可以使用BehaviorSubject
。在这里您可以设置默认值。
示例:
private user = new BehaviorSubject<string>('john');
在您的情况下:
private dateFilterSubject = new BehaviorSubject<{
startDate: Date;
endDate: Date;
}>({{value}});
有关更多信息,请参阅:
https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject
希望这会有所帮助。