Search code examples
angular6angular7angular8angular2-forms

Login and register is not working in angular8


I am trying login and register section using reactiveform method in angular 8 but not working.I am not getting any error but when I click submit or register button getting alert message like this :[object Object]. So I can not find the solution.Login and register process not working.If anyone kown please help me to resolve this issue.

Demo:https://stackblitz.com/edit/angular-7-registration-login-example-rfqlxg?file=app%2Fweb%2F_services%2Fuser.service.ts

user.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { User } from '../_models';

@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) { }

getAll() {
    return this.http.get<User[]>(`/users`);
}

getById(id: number) {
    return this.http.get(`/users/` + id);
}

register(user: User) {
    return this.http.post(`/users/register`, user);
}

update(user: User) {
    return this.http.put(`/users/` + user.id, user);
}

delete(id: number) {
    return this.http.delete(`/users/` + id);
}
}

authentication.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { User } from '../_models';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;

constructor(private http: HttpClient) {
    this.currentUserSubject = new      BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
    this.currentUser = this.currentUserSubject.asObservable();
}

public get currentUserValue(): User {
    return this.currentUserSubject.value;
}

login(username: string, password: string) {
    return this.http.post<any>(`/users/authenticate`, { username, password })
        .pipe(map(user => {
            // login successful if there's a jwt token in the response
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
                this.currentUserSubject.next(user);
            }

            return user;
        }));
}

logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
}
}

Solution

  • The reason why you are seeing [object Object] is because you are passing the entire HttpErrorResponse which is an object . Your alert component template will display it properly if it is not an object.

    you can change login form submit method as follows

    onSubmit() {
            this.submitted = true;
            // stop here if form is invalid
            if (this.loginForm.invalid) {
                return;
            }
    
            this.loading = true;
            this.authenticationService.login(this.f.username.value, this.f.password.value)
                .pipe(first())
                .subscribe(
                    data => {
                        this.router.navigate([this.returnUrl]);
                    },
                    error => {
                        this.alertService.error(error.message);
                        this.loading = false;
                    });
        }
    

    please change register components submit method as follows

     onSubmit() {
            this.submitted = true;
    
            // stop here if form is invalid
            if (this.loginForm.invalid) {
                return;
            }
    
            this.loading = true;
            this.authenticationService.login(this.f.username.value, this.f.password.value)
                .pipe(first())
                .subscribe(
                    data => {
                        this.router.navigate([this.returnUrl]);
                    },
                    error => {
                        this.alertService.error(error.message);
                        this.loading = false;
                    });
        }
    

    what i did is passed the message field from error response. if you want to have a logic for different http error codes , you can have it here and pass a message string to error method based on the error code. please try if you want to handle by error code

    onSubmit() {
            this.submitted = true;
    
            // stop here if form is invalid
            if (this.loginForm.invalid) {
                return;
            }
    
            this.loading = true;
            this.authenticationService.login(this.f.username.value, this.f.password.value)
                .pipe(first())
                .subscribe(
                    data => {
                        this.router.navigate([this.returnUrl]);
                    },
                    error => {
                        if(error.staus === 403){
                          this.alertService.error("You are not authorized");
                        }else{
                          this.alertService.error("Something went wrong");
                        }
                        this.loading = false;
                    });
        }
    }
    

    if you want to display the error as it is change the alert compoenent template as follows

    <div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text |json}}</div>