print Eventemitter data at angular 2

Asked

Viewed 325 times

1

personal ask me a question I researched more did not find answer yet I have an object inside a auth.service The code of the.Component app

import { Component} from '@angular/core';
import { AuthService } from './login/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  authNavShow: boolean = false;

  constructor(private authService: AuthService){

  }

  ngOnInit(){
    this.authService.authNav.subscribe(
      mostrar => this.authNavShow = mostrar,
    );

    console.log(this.authService.userData);

    if(this.authNavShow != true){
      var auth: boolean = true;

    }


  }
}

the auth.service code

import { Injectable,EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  constructor(private http: Http, private router: Router) { }

  private userAuth: boolean = false;

  authNav = new EventEmitter<boolean>();

  userData = new EventEmitter();

  fazerLogin(dataLogin){

    this.http.post(`http://localhost:88/login`, 
    JSON.stringify(dataLogin))
    .map(dados => dados.json())
    .subscribe(dados => this.checkLogin(dados)
    );

  }

  checkLogin(dados){

    if(dados.success == true){
      this.userAuth = true ;
      this.authNav.emit(true);

      this.userData.emit(dados);

      this.router.navigate(['/']);
    }

  }

  userAuthenticated(){
    return this.userAuth;
  }
}

what I need is to pull the data from the object in my app.Component but I don’t know any way or means, if anyone can help me thank you very much!

  • it takes a little more code; however, if in your app.component.ts doings subscribe() at the service.userData you should have its value

  • it would be interesting for you to edit your question by adding the code of app.component.ts and auth.service instead of putting them as an answer.

1 answer

1


In the ngOnInit of your app.component.ts you’ll have to do the same thing you did with the this.authService.authNav

  ngOnInit(){
        this.authService.userData.subscribe(data => this.userData = data);
        this.authService.authNav.subscribe(mostrar => this.authNavShow = mostrar);
  }

then you will have to start a this.authNavShow, only under the name of userData

  • hehe worked, thank you very much! I am beginner with the angular 2 there I have many doubts still, one more day I arrive there

Browser other questions tagged

You are not signed in. Login or sign up in order to post.