我在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()observable获得完整响应,我就将用户发送到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
答案 0 :(得分:1)
根据您的代码(基本上是正确的)和测试,您的问题是为每个需要它的组件重新创建UserService
。您需要将其设为&#34;单例服务&#34;,这意味着单个实例将与所有需要它的组件共享。
我不熟悉Ionic。您可以尝试这里one thread。如果它没有帮助,我建议你打开第二个问题,询问如何让你的UserService成为Ionic中的单身人士。
显然,更改DashboardPageComponent
的构造函数以将_user
属性声明为公共而非私有将允许Ionic注入相同的实例而不是创建新实例。 https://forum.ionicframework.com/t/rc0-typescript-private-vs-public-keyword/64863