如何使用AngularFire2创建用户使用电子邮件和密码登录 [英] How to create user Login with email and password using AngularFire2

查看:333
本文介绍了如何使用AngularFire2创建用户使用电子邮件和密码登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 login-service ,其中包含用google,facebook或twitter登录的选项,它运行的很好。



我正尝试创建用电子邮件和密码登录的选项(该选项在Firebase控制台中启用),我无法使其工作。



我的登录服务代码如下:

$ p $ import {从@角度/核心'注入,OnInit};
从angularfire2 / angularfire2导入{AngularFire,AuthProviders,AuthMethods};

$ b @Injectable()
导出类LoginService实现OnInit {
public isLoged:boolean;

ngOnInit(){

}

构造函数(private AF:AngularFire){
this.af.auth.subscribe => {
if(user){
this.isLoged = true;
console.info(Se ha logueado correctamente)
} else {
this .isLoged = false;
console.info(Se ha deslogueado correctamente);
}
});


login(){
this.af.auth.login();


loginGoogle(){
//这是默认的登录名,它在main.js中设置
this.login(); $ {
}

login Facebook(){
this.af.auth.login({
provider:AuthProviders.Facebook,
method:AuthMethods.Redirect
});


loginTwitter(){
this.af.auth.login({
provider:AuthProviders.Twitter,
method:AuthMethods.Redirect
});


createUser(email:string,password:string){
this.af.auth.createUser({email:email,password:password});

$ b loginWithPassword(){
this.af.auth.login({

提供者:AuthProviders.Password,
方法: AuthMethods.Password
))
}

logOut(){
this.af.auth.logout();
}

}

main.ts是:
$ b

 从'@ angular / common'导入{APP_BASE_HREF}; 
从'@ angular / forms'导入{disableDeprecatedForms,provideForms};
从'@ angular / core'导入{enableProdMode};
从'@ angular / platform-b​​rowser-dynamic'导入{bootstrap};

从'./app.routes'导入{APP_ROUTER_PROVIDERS};
从'./app.component'导入{AppComponent};
从angularfire2 / angularfire2中导入{
FIREBASE_PROVIDERS,defaultFirebase,firebaseAuthConfig,AuthProviders,
AuthMethods
};

if('<%= ENV%>'==='prod'){enableProdMode(); }

/ **
*引导应用程序并使ROUTER_PROVIDERS和APP_BASE_HREF可用。
*请参阅https://angular.io/docs/ts/latest/api/platform-b​​rowser-dynamic/index/bootstrap-function.html
* /
bootstrap(AppComponent, [
disableDeprecatedForms(),
provideForms(),
APP_ROUTER_PROVIDERS,
{
提供:APP_BASE_HREF,
useValue:'<%= APP_BASE%> ;'
},
FIREBASE_PROVIDERS,
defaultFirebase({//这个数据被替换为
apiKey:'apiKey',
authDomain:'authDomain',
databaseURL:'databaseURL',
storageBucket:'storageBucket',
}),
firebaseAuthConfig({
provider:AuthProviders.Google,
method:AuthMethods.Popup ,
})
]);

更新

正如@JS_astronauts所说,问题与数据如何传递给登录服务有关,现在我发现从loginService调用没有得到正确的参数,我正在使用FormBuilder: / p>

login.component.ts


$ b

  import {Component,OnInit} from '@角/芯'; 
从'@ angular / common'导入{FormBuilder,Validators,ControlGroup,NgFormModel}
从'angularfire2'导入{AngularFire,AuthProviders,AuthMethods};
从'../shared/login-service/login.service'
导入{LoginService}从@ angular / router导入{路由器};
$ b @Component({
moduleId:module.id,
selector:'login',
templateUrl:'login.component.html',
styleUrls:['login.component.css'],
指令:[NgFormModel]
})
导出类LoginComponent实现OnInit {

loginForm:ControlGroup;

构造函数(private router:Router,
private fb:FormBuilder,
private loginService:LoginService){

this.loginForm = fb.group {
name:[,Validators.required],
correo:[,Validators.required],
contrasena:[,Validators.required]
} )

$ b ngOnInit(){
}

loginWithPassword(){
this.loginService.createUser(
this .loginForm.controls ['correo'] .value.toString(),
this.loginForm.controls ['contrasena'] .value.toString()
);

if(this.loginService.isLoged){
this.router.navigate(['./ ejemplo']);





在html中我有:

 < form [ngFormModel] =loginForm(submit)=loginWithPassword()> 
< div id =DIV_13>
< div id =DIV_14>
< span id =SPAN_15> < i id =I_16>脸部< / i>< / span>
< div id =DIV_17>
< input ngControl =nametype =textplaceholder =First Name ...id =INPUT_18/>< span id =SPAN_19>< / span>
< / div>

< / div>
< div id =DIV_20>
< span id =SPAN_21> < i id =I_22>电子邮件< / i>< / span>
< div id =DIV_23>
< input ngControl =correotype =textplaceholder =Email ...id =INPUT_24/>< span id =SPAN_25>< / span>
< / div>
< / div>
< div id =DIV_26>
< span id =SPAN_27> < i id =I_28> lock_outline< / i>< / span>
< div id =DIV_29>
< input ngControl =contrasenatype =passwordplaceholder =Password ...id =INPUT_30/>< span id =SPAN_31>< / span>
< / div>
< / div>
< / div>

< div id =DIV_32>
< button type =submitid =A_33>开始< /按钮>
< / div>
< / form>

但是我得到的值是
this.loginForm.controls ['correo'] .value.toString()
等于null,所以我怎么得到这个值?



任何想法在哪里是问题?关于罗伯托。

解决方案

我发现了这个问题,问题是我需要放入[] ngFormModel在html中,并将指令FORM_DIRECTIVES添加到logig.component.ts上的组件。



使用ngFormModel我在控制台中得到一条消息,警告我这个指令将会在下一个RC中被选入,而
最终将被移除以支持新的表单模块,所以这个实现在将来不会工作。


I have created a login-service with the options to log in with google, facebook or twitter, and it is working well.

I am trying to create the option to log in with an email and a password (the option is enabled in the firebase console), and I am not able to make it work.

My login-service code is the following :

import {Injectable, OnInit} from '@angular/core';
import {AngularFire, AuthProviders, AuthMethods} from "angularfire2/angularfire2";


@Injectable()
export class LoginService implements OnInit {
public isLoged: boolean;

ngOnInit() {

}

constructor(private af: AngularFire) {
  this.af.auth.subscribe(user => {
    if (user) {
      this.isLoged = true;
      console.info("Se ha logueado correctamente")
    } else {
      this.isLoged = false;
      console.info("Se ha deslogueado correctamente");
    }
  });
}

login() {
  this.af.auth.login();
}

loginGoogle() {
  //this is the default login , that it's setup in the main.js
  this.login();
}

loginFacebook() {
  this.af.auth.login({
    provider: AuthProviders.Facebook,
    method: AuthMethods.Redirect
  });
}

loginTwitter() {
  this.af.auth.login({
    provider: AuthProviders.Twitter,
    method: AuthMethods.Redirect
  });
}

createUser(email: string, password: string) {
  this.af.auth.createUser({ email: email, password: password });
}

loginWithPassword() {
  this.af.auth.login({

    provider: AuthProviders.Password,
    method: AuthMethods.Password
  })
}

logOut() {
  this.af.auth.logout();
}

}

And the main.ts is :

import { APP_BASE_HREF } from '@angular/common';
import { disableDeprecatedForms, provideForms } from '@angular/forms';
import { enableProdMode } from '@angular/core';
import { bootstrap } from '@angular/platform-browser-dynamic';

import { APP_ROUTER_PROVIDERS } from './app.routes';
import { AppComponent } from './app.component';
import {
  FIREBASE_PROVIDERS, defaultFirebase, firebaseAuthConfig, AuthProviders,
  AuthMethods
} from "angularfire2/angularfire2";

if ('<%= ENV %>' === 'prod') { enableProdMode(); }

/**
 * Bootstraps the application and makes the ROUTER_PROVIDERS and the APP_BASE_HREF available to it.
 * @see https://angular.io/docs/ts/latest/api/platform-browser-dynamic/index/bootstrap-function.html
 */
bootstrap(AppComponent, [
  disableDeprecatedForms(),
  provideForms(),
  APP_ROUTER_PROVIDERS,
  {
    provide: APP_BASE_HREF,
    useValue: '<%= APP_BASE %>'
  },
  FIREBASE_PROVIDERS,
  defaultFirebase({ //this data is replaced
    apiKey: 'apiKey',
    authDomain: 'authDomain',
    databaseURL: 'databaseURL',
    storageBucket: 'storageBucket',
  }),
  firebaseAuthConfig({
    provider: AuthProviders.Google,
    method: AuthMethods.Popup,
  })
]);

Update :

As @JS_astronauts said , the problem is related with how the data is passed to the login service , right now I found that from the call to the loginService doesn't get the params right , I am using FormBuilder like this :

login.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, Validators, ControlGroup ,NgFormModel} from '@angular/common'
import {AngularFire, AuthProviders, AuthMethods} from 'angularfire2';
import {LoginService} from '../shared/login-service/login.service'
import {Router} from "@angular/router";

@Component({
    moduleId: module.id,
    selector: 'login',
    templateUrl: 'login.component.html',
    styleUrls : ['login.component.css'],
    directives : [NgFormModel]
})
export class LoginComponent implements OnInit {

    loginForm : ControlGroup;

    constructor(private router: Router,
                private fb : FormBuilder,
                private loginService : LoginService) {

      this.loginForm = fb.group({
        name : ["" , Validators.required],
        correo : ["" , Validators.required],
        contrasena :["",Validators.required]
      })
    }

    ngOnInit() {
    }

    loginWithPassword(){
      this.loginService.createUser( 
        this.loginForm.controls['correo'].value.toString() ,
        this.loginForm.controls['contrasena'].value.toString()
      );

  if(this.loginService.isLoged ){
    this.router.navigate(['./ejemplo']);
  }
}
}

And in the html I have :

 <form [ngFormModel]="loginForm" (submit)="loginWithPassword()">
    <div id="DIV_13">
      <div id="DIV_14">
        <span id="SPAN_15"> <i id="I_16">face</i></span>
        <div id="DIV_17">
          <input ngControl="name" type="text" placeholder="First Name..." id="INPUT_18" /><span id="SPAN_19"></span>
        </div>

      </div>
      <div id="DIV_20">
        <span id="SPAN_21"> <i id="I_22">email</i></span>
        <div id="DIV_23">
          <input ngControl="correo"  type="text" placeholder="Email..." id="INPUT_24" /><span id="SPAN_25"></span>
        </div>
      </div>
      <div id="DIV_26">
        <span id="SPAN_27"> <i id="I_28">lock_outline</i></span>
        <div id="DIV_29">
          <input  ngControl="contrasena" type="password" placeholder="Password..." id="INPUT_30" /><span id="SPAN_31"></span>
        </div>
      </div> 
    </div>

    <div id="DIV_32">
      <button type="submit" id="A_33">Get Started</button>
    </div>
    </form>

But the value that I get with this.loginForm.controls['correo'].value.toString() is equal to null , so how I get the value ?

Any idea where is the problem? Regards Roberto.

解决方案

I have found the problem , the problem was that i need to put into " [ ] " the directive of ngFormModel in the html, and add the directive "FORM_DIRECTIVES" to the component on the logig.component.ts.

PS : using ngFormModel I get an info message in the console , warning me about that this directive will be opt-in in the next RC, and will eventually be removed in favor of the new forms module , so this implementation won't work in a future

这篇关于如何使用AngularFire2创建用户使用电子邮件和密码登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆