我有app.component.ts,它是父级和两路登录和注册。
在我的注册视图中,注册确认后,我想传递自动登录视图。
register.component.ts
onSubmit() {
let params = {
mobile:this.registrationForm.value.mobile,
password:this.registrationForm.value.password
}
this.sharedService.emitChange({origin:"login", credentials:params });
}login.component.ts (我的订阅不起作用)
constructor(private fb: FormBuilder, private sharedService: SharedService) {
sharedService.changeEmitted$.subscribe( // not working
text => {
console.log(text);
if (text.origin == 'login') this.login(text.credentials);
});
}app.component.ts (这是有效的)
sharedService.changeEmitted$.subscribe(
text => {
if (text.origin == 'login'){};
});希望我说的很清楚。我有两个视图,登录和注册,以及如何在这两个ts文件之间进行通信。我做得对吗?
发布于 2017-03-03 09:46:36
我猜问题是,在创建SharedService之前,LoginComponent会发出这些更改。这就是为什么它在AppComponent中工作,而不是在LoginCOmponent中工作的原因。
一个可能的解决方案是使用ReplaySubject。
ReplaySubject允许您定义chche计数n。然后,它将保存最后发出的n,并将所有这些通知新的Subscription。
因此,在您的情况下,您应该使用new ReplaySubject<>(1)。
订阅此ReplaySubject的每个人现在都将得到最后发出的值。
发布于 2017-03-03 10:23:30
我不能评论,我会把这个写下来作为回答。
在创建LoginComponent之前,您正在发出文本。在发出文本之前,LoginComponent应该在那里侦听事件。
解决这个问题的一个解决方案是使用localStorage
register.component.ts:
params = {
mobile:'mobile',
password:'password'
}
onSubmit(): void {
console.log("putting in localStorage")
localStorage.setItem('params', JSON.stringify(this.params))
}login.component.ts
params:any
ngOnInit(): void {
console.log("getting from localStorage")
this.params = JSON.parse(localStorage.getItem('params'))
console.log(this.params)
}希望这能帮上忙!
https://stackoverflow.com/questions/42575049
复制相似问题