Javascript

Angular – Firebase Authentication using Email Password

In this post, you will learn about angular code sample or example related to firebase authentication using email and password in an Angular app. The code has been tested with Angular 7.* and latest version of AngularFire. You will learn some of the following in this post:

  • Login code example using Firebase Method, signInWithEmailAndPassword
  • LoginComponent code for invoking Firebase Authentication using AuthService



Login Code Example using Firebase Method, signInWithEmailAndPassword

The code could be put inside a file such as auth.service.ts. Pay attention to the fact that an instance of Observable is returned from the login api.

@Injectable({
  providedIn: 'root'
})
export class AuthService {

 login(user: User): Observable<GenericResponse> {
    const response = new GenericResponse();
    const signupSubj = new Subject<GenericResponse>();
    const result = signupSubj.asObservable();
    this.afAuth.auth.signInWithEmailAndPassword(user.username, user.password)
      .then((fbuser) => {
        response.messagecode = 'USER_LOGIN_SUCCESS';
        response.message = 'user login successful!';
        signupSubj.next(response);
      })
      .catch(function (err){
        response.errorcode = err.code;
        response.errormsg = err.message;
        signupSubj.next(response);
      });
    return result;
 } 
}

In the above code, a GenericResponse object is used for capturing the error message details. The following represents the code for GenericResponse object. The code be saved in a seperate file and exported.

export class GenericResponse {
  public errorcode = '';
  public errormsg = '';
  public message = '';
  public messagecode = '';
  constructor() {}
}

Also, a User object is passed to login API as an input parameter. Here is the code for sample User object. The code be saved in a separated file and imported in the auth.service.ts.

export class User {
  public id = '';
  public username = '';
  public password = '';
  public nickname = '';
}

LoginComponent code for invoking Firebase Authentication using AuthService

Here is the code for LoginComponent which invokes above shown login API on AuthService instance.

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  user: User;

  constructor(private authService: AuthService, private router: Router) {
    this.user = new User();
  }

  onSubmit() {
    this.authService.login(this.user).subscribe(response => {
      if (response.errormsg !== '') {
 //
 // Display error message for login failure
 //
      } else {
 //
 // Redirect to home page on successful login
 //
        this.router.navigate(['/home']);
      }
    });
  }
}

References

Summary

In this post, you learned about Angular and AngularFire code examples which would help you quickly create firebase login authentication using email and password. In later posts, you will learn about Route Guards and AngularFireAuth. Hope you liked the post. Do feel free to share your comments or suggestions.

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Share
Published by
Ajitesh Kumar

Recent Posts

Retrieval Augmented Generation (RAG) & LLM: Examples

Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…

6 days ago

How to Setup MEAN App with LangChain.js

Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…

2 weeks ago

Build AI Chatbots for SAAS Using LLMs, RAG, Multi-Agent Frameworks

Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…

2 weeks ago

Creating a RAG Application Using LangGraph: Example Code

Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…

3 weeks ago

Building a RAG Application with LangChain: Example Code

The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…

3 weeks ago

Building an OpenAI Chatbot with LangChain

Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…

3 weeks ago