【发布时间】:2016-10-04 15:23:56
【问题描述】:
我在 Ionic2/RC0 上,我正在为我的应用程序实现用户服务。
@Injectable()
export class UserService {
UserWhatever: ReplaySubject<User> = new ReplaySubject<User>();
constructor(private _util: UtilService,
private _app: AppService,
private _http: Http) {
console.log("I am UserService. Just got created")
this.UserWhatever.subscribe(
(data) => {
console.log("User service got a USER");
}
)
}
login(element) {
return this.getToken(element).flatMap(
(data) => {
return Observable.forkJoin([Observable.of(data),
this.readUser(data)
]);
}
).map(data => {
localStorage["jwt"] = data[0];
this._util.sendToast("logged");
console.log("Http call received a USER")
let guser: User = data[1];
console.log("Called next ")
this.UserWhatever.next(guser)
});
}
当我从 HomeComponent 中可观察的 login() 获得完整响应后,我将用户发送到 DashboardComponent
export class LoginComponent implements OnInit {
subs() {
this._user.UserWhatever.subscribe(
(data) => {
console.log("Login Component got a Replayed USER");
})
}
login() {
this.isDisabled = true;
this._user.login(this.loginForm)
.subscribe(
data => {
this.subs()
this.nav.push(DashboardPageComponent);
}
}
我从我的 userService 订阅 ReplaySubject。这里是问题出现的地方。它不会在订阅时重播主题。如果我碰巧在 ReplaySubject 上再次调用 next(),一切正常。
export class DashboardPageComponent implements OnInit, OnDestroy, AfterViewInit {
public user: User;
constructor(private _app: AppService,
private _device: DeviceService,
private _user: UserService,
private _store: Store<any>,
private _nav: NavController) {
console.log("Dashboard component")
}
ngOnInit() {
this._user.UserWhatever.subscribe(
(data) => {
this.user = data;
console.log("Dashboard finally received a User")
console.log(data)
}
)
}
这一切都像常规的 Rxjs.Subject() 一样工作,但我需要重播功能。我在 rxjs.beta-12
更新日志
I am UserService. Just got created
Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
Http call received a USER
Called next
User service got a USER
Login Component got a Replayed USER
I am UserService. Just got created
Dashboard component
【问题讨论】:
-
我喜欢问题标题
....doesn't replay...;) he he!!! -
您确定将 same
UserService实例注入到DashboardPageComponent和LoginComponent中吗?DashboardPageComponent是否有可能获得一个 new 实例(因此是新的空ReplaySubject)? -
@Brandon 我怎么确定?如果这就是你的意思,我正在从同一个文件中导入。我很确定这就是正在发生的事情,但不知道为什么。如果我后来碰巧打电话给下一个,订阅就会起作用
-
在UserService构造函数中放一个console.log语句,看看它打印了多少次。
-
@Brandon 在创建时看起来像
this.nav.push(DashboardPageComponent);create another another UserService。这应该发生吗?