Angular中的登录和HTTP POST问题

时间:2019-05-15 13:40:56

标签: javascript angular

我试图在Angular App中实现一个登录系统,但是它重定向到主视图,并将空对象保存到Local Storage中,而不会按我在表格中键入的内容正确或伪造的帐户电子邮件和密码。这是我的第一个实际项目,也是第一次制作登录系统。一致地,我无权在此处显示真实的API。 代码:

login.component.html

<div class="content">
  <div fxLayout="column" fxLayoutAlign="center center">
    <mat-card class="example-card">
      <mat-card-header>
        <mat-card-title>Dobrodošli!</mat-card-title>
      </mat-card-header>
      <mat-card-content>
        <img class="logo" src="../../assets/dnevnimeni.svg" alt="">
        <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
          <mat-form-field>
            <input matInput type="email" placeholder="E-Mail" formControlName="email">
            <mat-error *nfIf="">Unesite odgovarajući E-Mail</mat-error>
          </mat-form-field> <br>
          <mat-form-field>
            <input matInput type="password" placeholder="Password" formControlName="password">
            <mat-error *ngIf="">Unesite validan password</mat-error>
          </mat-form-field> <br>
          <button mat-stroked-button>Login</button>
        </form>
      </mat-card-content>
    </mat-card>
  </div>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

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

  loginForm: FormGroup;
  submitted = false;
  returnUrl: string;
  error: {};
  loginError: string;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private authService: AuthService
    ) { }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.authService.logout();
  }

  get email() { return this.loginForm.get('email'); }
  get password() { return this.loginForm.get('password'); }

  onSubmit() {
    this.submitted = true;
    this.authService.login( this.email.value, this.password.value).subscribe((data) => {

       if (this.authService.isLoggedIn) {
            const redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/';
                this.router.navigate([redirect]);
      } else {
            this.loginError = 'email or password is incorrect.';
    }
      },
      error => this.error = error
    );
    console.log(this.authService.restaurant.email);

  }
}

和auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';


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

  loginUrl = 'xxxxxxxx';
  errorData: {};

  restaurant: Restaurant;

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = "email=" + email + "&password=" + password;
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
        }
      }),
      catchError(this.handleError)
    );
  }


  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
    return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }
}

3 个答案:

答案 0 :(得分:0)

您的帖子数据应类似于var postData = {email:email,password:password},但是您已经描述了带有查询参数的get请求。 将数据保存在可观察的数据流中也是一种不好的做法。每个新订户再次触发该代码的执行

        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
        }

答案 1 :(得分:0)

在map函数中,您不返回任何值,而是尝试在对象中转换后请求中发送的参数;

login(email: string, password: string) {
let postData = {email : email ,password :password};
return this.http.post<Restaurant>(this.loginUrl, postData)
.pipe(map(restaurant => {
    if (restaurant) {
      localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
      return restaurant;
    }
  }),
  catchError(this.handleError)
);
}

答案 2 :(得分:0)

postData应该是对象而不是字符串。还可以通过console.log中的isLoggedIn()检查localStorage.getItem('currentRestaurant')返回的数据,如果它具有"{}""null"之类的值,则它将在if语句中返回true。

isLoggedIn() {
if (localStorage.getItem('currentRestaurant')) {
  return true;
}
return false; }