How to implement the google login in angular 4

时间:2018-02-03 10:59:20

标签: angular typescript firebase firebase-authentication angularfire2

I am pretty new to the angular world, now am stuck with a problem in implementing the google login. I have created a button which on click will redirect me to google login page and from there after signing in the users will get redirected to the homepage. The main problem is that the login details are not stored in my firebase console. I don't know what is causing this error. So I'm sharing my code :

login.component.html

<button mat-raised-button color="warn" (click)="login()" >Login with google</button>

login.component.ts

import { Component, OnInit, Inject } from '@angular/core';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';


@Component({
  selector: 'mt-login',
  templateUrl: './mt-login.component.html',
  styleUrls: ['./mt-login.component.css']
})
export class MtLoginComponent {

  constructor(private afAuth: AngularFireAuth ){}

  login() {
    return this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider()).catch(err => {console.log(err)});
  }
}

1 个答案:

答案 0 :(得分:0)

您必须订阅onAuthStateChanged observable才能接收身份验证状态更改。

import { Component, OnInit, Inject } from '@angular/core';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';

@Component({
  selector: 'mt-login',
  templateUrl: './mt-login.component.html',
  styleUrls: ['./mt-login.component.css']
})
export class MtLoginComponent implements OnInit {

  constructor(private afAuth: AngularFireAuth ){}

  ngOnInit() {
    this.afAuth.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
  }

  login() {
    return this.afAuth.auth
      .signInWithRedirect(new firebase.auth.GoogleAuthProvider())     
      .catch(err => {console.log(err)});
  }
}