我有一个调用REST api来获取一些信息的组件。当这些信息准备好后,我需要另一个组件来使用它们。这些组件是兄弟组件。为了实现这一点,我使用了服务和主题。接下来更新值。另一个组件需要侦听更改。这就是我正在做的:
组件:
this.restService.getInfos().subscribe(i => {
this.updatingService.profileLoadedEvent(i)
});
更新服务:
userInfo = new Subject<any>();
public profileLoadedEvent(info: string) {
this.userInfo.next(info);
}
public getProfileLoadedEvent(): Observable<string> {
return this.userInfo.asObservable();
}
组件B:
this.updatingService.getProfileLoadedEvent().subscribe((info: string) => {
this.doSomething(info);
})
我的问题是组件B从来没有得到做某事()。组件A正确调用userInfo。下一个
return this.userInfo.asObservable();
没有被调用。嗯,在组件a调用profileLoadedEvent
方法之前,它只被调用一次。
我做错了什么?
你的服务每次调用函数都会创建一个新的可观察对象,这取决于发送内容的时间和函数调用来获取可观察对象的时间,你将不会收到任何东西。你可以把它改成:
@Injectable({
providedIn: 'root'
})
export class updatingService {
private: userInfo = new Subject<any>();
userInfo$ = this.userInfo.asObservable();
public profileLoadedEvent(info: string) {
this.userInfo.next(info);
}
public getProfileLoadedEvent(): Observable<string> {
return this.userInfo$;
}
}
尝试使用BehaviorSubject
代替Subject
,我用这种方式解决了同样的问题。
import { BehaviorSubject } from 'rxjs';
userInfo: BehaviorSubject<any> = new BehaviorSubject({});
getUserInfo() {
return this.userInfo.asObservable();
}
组件:
this.restService.getUserInfo().subscribe((info:any) => {
this.doSomething(info);
});
点击这个链接来理解BehaviorSubject vs Observable?