Angular2将服务传递给本地组件变量

时间:2016-12-14 06:29:19

标签: angular

我想要做的是让我的变量loggedIn验证用户是否已登录到我的Angular2 Firebase应用。到目前为止没有任何反应,我没有任何错误。

正确输入了

authService,因此没有错误。出于这个原因,我没有在代码中包含我的构造函数。

isuser是我的nav.component中的局部变量,我希望将isuser值设置为服务isLogged值。

我的 auth.service.ts

import { Injectable, EventEmitter } from '@angular/core';
import { User } from './user.interface';

declare var firebase: any;

@Injectable()
export class AuthService {

public loggedIn = new EventEmitter<boolean>();

    signinUser(user: User){
        firebase.auth().signInWithEmailAndPassword(user.email, user.password)
        .catch(function(error){
            console.log(error);
        });
    }

    isLogged(showLog: boolean){this.loggedIn.emit(showLog);}
    logout(){firebase.auth().signOut();}

}

我的 app.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from './shared/auth.service';

declare var firebase: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {

constructor(private authService: AuthService){}

ngOnInit(){
    var self = this;
    var user = firebase.auth().currentUser;
    if (user){this.authService.isLogged(true);}
    else {this.authService.isLogged(false);}
}

}

我的 nav.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../shared/auth.service';
import { FormGroup, FormControl } from '@angular/forms';

declare var firebase: any;

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html'
})
export class NavigationComponent implements OnInit {
    signInForm: FormGroup;
    private isuser: boolean;

  constructor(private authService: AuthService){
    this.signInForm = new FormGroup({
        'email': new FormControl(),
        'password': new FormControl()
    });
  }

  onSignup(){
    this.authService.signinUser(this.signInForm.value);
  }

  onLogout(){
    this.authService.logout();
  }

  ngOnInit(){
    var self = this;
    this.authService.loggedIn.subscribe(
    retuser => self.isuser = retuser);
  }

}

我的 navigation.component.html

<div id="signIn" *ngIf="!isuser">
    <form [formGroup]="signInForm" (ngSubmit)="onSignup()" class="form-inline">
        <input type="text" class="form-control" placeholder="email" formControlName="email" />
        <input type="password" class="form-control" placeholder="password" formControlName="password" />
        <button class="btn btn-info">Sign In</button>
    </form>
</div>

<div id="signedIn" *ngIf="isuser">
    <p>Welcome dude</p>
    <p>View Profile</p>
    <p (click)="onLogout()">Log Out</p>
</div>

为了进一步澄清,我试图模仿的是以下代码:

isAuthenticated(){
    var user = firebase.auth().currentUser;
    if (user){return true;}
    else {return false;}
}

我希望代码在 auth.service 上以相同的方式运行。而不是使用我想要使用事件发射器的功能。

0 个答案:

没有答案