I'm trying to implement a "remember me" checkbox in my login form.
I created the project with Angular CLI 12.2.9
, firebase 9.4.0
and @angular/fire 7.4.0
I have the following service auth.service.ts
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import { Auth } from '@angular/fire/auth';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private auth: Auth) {
}
public async setPersistence(persistence: boolean): Promise<void> {
if (persistence) {
await this.auth.setPersistence({ type: 'SESSION' });
} else {
await this.auth.setPersistence({ type: 'NONE' });
}
}
}
The Persistance interface in @angular/fire/auth
is the following:
/**
* An interface covering the possible persistence mechanism types.
*
* @public
*/
export declare interface Persistence {
/**
* Type of Persistence.
* - 'SESSION' is used for temporary persistence such as `sessionStorage`.
* - 'LOCAL' is used for long term persistence such as `localStorage` or `IndexedDB`.
* - 'NONE' is used for in-memory, or no persistence.
*/
readonly type: 'SESSION' | 'LOCAL' | 'NONE';
}
For some reason when I call setPersistence
in my component I get the following error:
This is my component:
import { AuthService } from './../../services/auth.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { emailRegex } from './email.regex';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
public login: FormGroup;
constructor(private fb: FormBuilder, private auth: AuthService) {
this.login = this.fb.group({
email: ['', [Validators.required, Validators.pattern(emailRegex)]],
password: ['', Validators.required],
rememberMe: false,
});
}
public ngOnInit(): void {
this.login.get("rememberMe")?.valueChanges.subscribe((p: boolean) => {
this.auth.setPersistence(p).then((res) => {
console.log("Changed success");
})
});
}
}
What am I doing wrong? And if this is not the correct way to change the User auth persistence please guide me through the correct path. Thanks in advance.
CodePudding user response:
it seems it expect objects, that are already in library. for example:
.setPersistance(Auth.Persistence.SESSION)
CodePudding user response:
I fixed it by making the following imports:
import { Injectable } from '@angular/core';
import {
Auth,
} from '@angular/fire/auth';
import {
setPersistence,
inMemoryPersistence,
browserSessionPersistence,
Persistence,
} from '@firebase/auth';
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(
private auth: Auth,
) {
}
public async setPersistence(persistence: boolean): Promise<void> {
const type: Persistence = persistence
? browserSessionPersistence
: inMemoryPersistence;
await setPersistence(this.auth, type);
}
}