登录和注册在角度 8 中不起作用

Login and register is not working in angular8

我正在尝试使用 angular 8 中的 reactiveform 方法登录和注册部分,但不是 working.I 我没有收到任何错误,但是当我单击提交或注册按钮时收到如下警告消息:[object目的]。所以我找不到 solution.Login 并且注册过程不是 working.If 谁知道请帮我解决这个问题。

演示: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);
}
}

您看到 [object Object] 的原因是因为您传递的是整个 HttpErrorResponse,它是一个对象。如果它不是对象,您的警报组件模板将正确显示它。

您可以更改登录表单提交方式如下

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

请修改注册组件提交方式如下

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

我所做的是从错误响应中传递消息字段。如果你想有不同的 http 错误代码的逻辑,你可以在这里有它,并根据错误代码将消息字符串传递给错误方法。如果您想按错误代码

处理,请尝试
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;
                });
    }
}

如果您想按原样显示错误 更改警报组件模板如下

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