0

I have a problem to pass a subscribed value to another component.

Structur:

app/
---elements/
------navigation.component.ts
---pages/
------login/
----------login.component.ts

login.component.ts

isAuthenticated: any = false;

  onSignin() {
    this.authService.signinUser(this.myForm.value)
      .subscribe(
        data => {
          this.isAuthenticated = data;
        });
  }

this.isAuthenticated is true if the login was successful.

What is the best way to send the data of isAuthenticated to the navigation.component.ts?

navigation.component.ts

isAuthenticated: any = false;

  constructor (private authService: AuthService, private router: Router) {
    this.authService.isAuthenticated()
      .subscribe(data => {
        this.isAuthenticated = data;
      });
  }

Added: auth.service.ts

isAuthenticated() {

      if (this.currentUser != null) {

        const token = this.currentUser.token;

        const body = JSON.stringify({token: token});
        return this.http.post('https://test.com/src/v13n22214', body)
          .map((response: Response) => {
            const authResponse = response.json().response;
            if (authResponse) {
              return true;
            } else {
              return false;
            }
          });
      }
Marcel
  • 381
  • 1
  • 5
  • 19
  • I think this might help you . http://stackoverflow.com/questions/41463343/get-the-value-returned-by-canactivate-method-in-angular2-route-in-a-component/41467816#41467816 – Rahul Singh Mar 30 '17 at 19:05

1 Answers1

0

You should save the value in the service then you can get it in another component, since you already injected the service

 constructor (private authService: AuthService, private router: Router) {
    this.isAuthenticated = this.authService.isAuthenticated();
 }
Roman C
  • 49,761
  • 33
  • 66
  • 176