Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6883

Angular 2 Passing Values across components

I have app.component.ts which is parent and two routes login and register

In my register view, after registration is confirmed i want to pass login view for autologin.

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 (My subscribe is not working)

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 (This is working)

sharedService.changeEmitted$.subscribe(
        text => {
          if (text.origin == 'login'){};
        });

Hope I was clear. I got two views, login and register and how to communicate between those two ts files. Am i doing it right?

Upvotes: 0

Views: 138

Answers (2)

elmiomar
elmiomar

Reputation: 2012

I cannot comment I will write this as an answer.

You are emitting your text before the creation of LoginComponent. The LoginComponent should be there listening on the event, before the text is emitted.

One solution to this, is to use 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)
}

hope this helps!

Upvotes: 0

Robert P
Robert P

Reputation: 9783

I guess, the problem is, that the SharedService emits the changes, before the LoginComponent is created. Thats why it works inside the AppComponent, but not in the LoginCOmponent.
A possible solution is to use ReplaySubject.
The ReplaySubject allows you to define a chche count n. It will then save the last n emits and notify new Subscriptions about all of them.
So in your case you should use a new ReplaySubject<>(1).
Everyone who subscribes to this ReplaySubject will now get the last emitted value.

Upvotes: 2

Related Questions