Angular 2跨组件传递值

时间:2017-03-03 09:24:49

标签: angular

我有app.component.ts,它是父和两条路线登录和注册

在我的注册视图中,注册确认后我想通过自动登录的登录视图。

register.component.ts

cat test.css | tr '\n' ' '

login.component.ts(我的订阅无效)

onSubmit() {
 let params = {
      mobile:this.registrationForm.value.mobile,
      password:this.registrationForm.value.password
    }
    this.sharedService.emitChange({origin:"login", credentials:params });
  }

app.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);
      });
  }

希望我很清楚。我有两个视图,登录和注册以及如何在这两个ts文件之间进行通信。我做得对吗?

2 个答案:

答案 0 :(得分:2)

我想问题是,SharedServiceLoginComponent创建之前发出了更改。这就是为什么它在AppComponent内部起作用,而不是在LoginCOmponent中起作用 可能的解决方案是使用ReplaySubject ReplaySubject允许您定义chche计数n。然后,它会保存最后n次发出并通知新Subscription所有这些内容 因此,在您的情况下,您应该使用new ReplaySubject<>(1) 订阅此ReplaySubject的所有人现在都将获得最后一次发布的值。

答案 1 :(得分: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)
}

希望这有帮助!