有没有办法从可观察的条件开始有条件地发射值?在我的情况下,.asObservable()
函数的订阅者只应在CurrentUser
初始化后获得第一个值。
export class CurrentUser {
private currentUser$: Observable<CurrentUser>;
private currentUserBehaviorSubject: BehaviorSubject<CurrentUser>;
public name: string = "";
constructor() {
this.currentUserBehaviorSubject = new BehaviorSubject(this);
this.currentUser$ = this.currentUserBehaviorSubject.asObservable();
}
public asObservable(): Observable<CurrentUser> {
//
if(user.name.length > 0){
return this.currentUser$;
}
else {
// ?????
}
}
public initialize(string name){
this.name = name;
this.currentUserBehaviorSubject.next(this);
}
}
export class SampleComponent {
constructor(
currentUser: CurrentUser
) {
currentUser.asObservable().subscribe(
(u: CurrentUser) => {
// i only want an INITIALIZED user here
},
error => {},
() => { }
);
}
}
答案 0 :(得分:3)
看起来您可以在asObservable()
方法中始终返回一个Observable,并使用skipUntil()
运算符抑制排放,直到currentUserBehaviorSubject
发出(我猜你知道怎么做) CurrentUser已初始化):
public asObservable(): Observable<CurrentUser> {
return this.currentUser$
.skipUntil(this.currentUserBehaviorSubject);
}
答案 1 :(得分:0)
我怎么看:
export class CurrentUser {
subject: Subject<CurrentUser> = new Subject<CurrentUser>();
observable: Observable<CurrentUser = this.subject.asObservable();
constructor() {
// Do your business
this.subject.next(this);
}
}
在您的组件中,只需订阅observable
属性。
这样,当您初始化新的CurrentUser时,会通知您的观察者。这是你想要的,还是我误解了?