2017-03-03 47 views
0

我有app.component.ts其是親和兩條路線登錄並註冊角2傳遞值

以我寄存器視圖,登記被證實後,我想通過用於自動登錄登錄視圖。

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文件之間進行通信。我做對了嗎?

+0

'SharedService'只提供一次嗎?只在一個'NgModule'中? – mxii

+0

我很抱歉。我無法理解。 –

+0

在任何'NgModule'中你都必須提供'SharedService'。這應該只發生一次! – mxii

回答

2

我想,問題是,該SharedService發射的變化,創建LoginComponent之前。這就是爲什麼它在AppComponent內工作,但不在LoginCOmponent
可能的解決方案是使用ReplaySubject
ReplaySubject允許你定義一個chche數n。然後它會保存最後的n發出並通知新的Subscription s關於他們所有。
所以在你的情況下,你應該使用new ReplaySubject<>(1)
大家誰同意這樣的ReplaySubject現在將得到最後的發射值。

0

我無法評論,我會寫這作爲一個答案。

你都散發創造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) 
} 

希望這幫助!