gpt4 book ai didi

angular - 如何使用 AngularFire2 使用电子邮件和密码创建用户登录名

转载 作者:太空狗 更新时间:2023-10-29 17:45:45 25 4
gpt4 key购买 nike

我已经创建了一个login-service,其中包含使用 google、facebook 或 twitter 登录的选项,并且运行良好。

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

我的登录服务代码如下:

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();
}

}

main.ts 是:

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,
})
]);

更新:

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

登录.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']);
}
}
}

在 html 中我有:

 <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>

但是我得到的值(value) this.loginForm.controls['correo'].value.toString() 等于 null ,那么我如何获得该值?

知道问题出在哪里吗?问候罗伯托。

最佳答案

如果您无法使用用户数据登录,那么数据如何传递到登录服务就会出现问题。

Plunker

这是一个使用用户服务的例子:

  import {Injectable} from '@angular/core';

@Injectable()
export class UserService {
public auth: any;
constructor() {
this.auth = firebase.auth();
}

public login(userEmail: string, userPassword: string) {
return new Promise((resolve, reject) => {
this.auth.signInWithEmailAndPassword(userEmail, userPassword)
.then(userData => resolve(userData),
err => reject(err));
});
}

public logout() {
return this.auth.signOut();
}
}

登录组件:

import { Component } from '@angular/core';
import { FORM_DIRECTIVES } from '@angular/common';
import { UserService } from './user.service';

@Component({
selector: 'login',
template: `
<form (ngSubmit)="login()">
<label for="userEmail">Email</label><br/>
<input type="email" required
[(ngModel)]="userEmail" >
<br/>
<label for="userPassword">Password</label><br/>
<input type="password" required
[(ngModel)]="userPassword" >
<hr/>
<button type="submit">Login!</button>
</form>
`,
directives: [FORM_DIRECTIVES],
providers: [UserService]
})
export class LoginComponent {
public userEmail: string;
public userPassword: string;
constructor(private _user: UserService) {}

public login() {
this._user.login(this.userEmail, this.userPassword)
}
}

简单的用户登录:

email: string;
pw: string;
authed: boolean;
constructor(private _us: UserService) {
this.authed = false;
}

signup() {
this._us.signUp(this.email, this.pw);
}

login() {
this._us.login(this.email, this.pw).then((res) => {
console.log(res);
if (res.provider === 4)
this.authed = true;
});
}

angularfire2: plunker

登录组件类:

export class App {
email: string;
pw: string;
authed: boolean;
constructor(private _us: UserService) {
this.authed = false;
}

signup() {
this._us.signUp(this.email, this.pw);
}

login() {
this._us.login(this.email, this.pw).then((res) => {
console.log(res);
if (res.provider === 4)
this.authed = true;
});
}

}

服务:

    import { Injectable } from '@angular/core';
import { AngularFire, FirebaseAuth } from 'angularfire2';

@Injectable()
export class UserService {
public db: any;
constructor(private af: AngularFire, private auth: FirebaseAuth) {

}

signUp(email: string, password: string) {
var creds: any = { email: email, password: password };
this.af.auth.createUser(creds);
}

login(email: string, password: string): Promise<boolean> {
var creds: any = { email: email, password: password };
var res: Promise<boolean> = new Promise((resolve, reject) => {
this.auth.login(creds).then(result => {
resolve(result);
})
});
return res;
}

}

自举:

    //main entry point
import {bootstrap} from '@angular/platform-browser-dynamic';
import {App} from './app';
import {
FIREBASE_PROVIDERS,
defaultFirebase,
firebaseAuthConfig,
AuthMethods,
AuthProviders
} from 'angularfire2';
import { UserService } from './user.service';

bootstrap(App, [
FIREBASE_PROVIDERS,
// Initialize Firebase app
defaultFirebase({
apiKey: "AIzaSyD6v-fYdZgeHtLfBctFqEQ4Ra7ZDpLZKug",
authDomain: "plnkr-1a222.firebaseapp.com",
databaseURL: "https://plnkr-1a222.firebaseio.com",
storageBucket: "plnkr-1a222.appspot.com",
}),
firebaseAuthConfig({
provider: AuthProviders.Password,
method: AuthMethods.Password
}),
UserService
])
.catch(err => console.error(err));

关于angular - 如何使用 AngularFire2 使用电子邮件和密码创建用户登录名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com