登录和寄存器在angular8中不起作用

问题描述 投票:-1回答:1

[我正在尝试使用angular8中的reactform方法登录和注册部分,但不起作用。我没有收到任何错误,但是当我单击Submit或register按钮时,得到这样的警报消息:[object Object]。因此,我找不到解决方案。登录和注册过程无法正常进行。如果有人知道,请帮助我解决此问题。

演示: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);
}
}
angular6 angular7 angular8 angular2-forms
1个回答
0
投票
看到[object 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>

© www.soinside.com 2019 - 2024. All rights reserved.