0

我一直在为我正在开发的应用程序使用虚拟身份验证。所以我已经使用虚拟本地用户成功实现了这一点。

不幸的是,当我试图让它与内存数据服务一起工作时,我遇到了障碍。我的用户数组返回未定义并且无法在控制台日志中将错误更改为字符串。下面是使用拦截器的假后端。

import { Injectable, OnInit } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';

import { User } from '@/data/models/property/user';
import { UserService } from '@/_services/user.service';

@Injectable()
export class FakeBackendInterceptor implements HttpInterceptor, OnInit {

  users: User[];

  constructor(private http: HttpClient, private userService: UserService) { }

  ngOnInit() {
    this.getAll();
  }
  private getAll(): void {
    this.userService.getAll()
      .subscribe(data => this.users = data);
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // authenticate
    if (request.url.endsWith('/users/authenticate') && request.method === 'POST') {
    // find if any user matches login credentials
      const filteredUsers = this.users.filter(user => {
        if (user.email === request.body.email && user.password === request.body.password) {
        return user;
        }
      });

    if (filteredUsers) {
      // if login details are valid return 200 OK with user details and fake jwt token
      const user = filteredUsers[0];
      const body = {
        id: user.id,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        studentNo: user.studentNo,
        isStaff: user.isStaff,
        token: 'fake-jwt-token'
      };

    return of(new HttpResponse({ status: 200, body: body }));
      } else {
        // else return 400 bad request
        return throwError({ error: { message: 'Email or password is incorrect' } });
      }
    }
    return next.handle(request);

  }
}

接下来是我的用户服务。

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

import { User } from '../data/models/property/user';

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

  getAll(): Observable<User[]> {
    return this.http.get<User[]>('api/users')
      .pipe(
        catchError(this.handleError('getAll', []))
      );
  }

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

  private handleError<T>(operation = 'operation', result ?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error.name); // log to console instead

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}

我怀疑这是我错过或不确定的事情。感激地收到任何帮助。

编辑:调试时出现 RangeError:超出最大调用堆栈大小

4

1 回答 1

1

return the error through hadlers catch

intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
    // authenticate
    if (request.url.endsWith('/users/authenticate') && request.method === 'POST') {
        // find if any user matches login credentials
        const filteredUsers = this.users.filter(user => {
            if (user.email === request.body.email && user.password === request.body.password) {
                return user;
            }
        });

        if (filteredUsers) {
            // if login details are valid return 200 OK with user details and fake jwt token
            const user = filteredUsers[0];
            const body = {
                id: user.id,
                email: user.email,
                firstName: user.firstName,
                lastName: user.lastName,
                studentNo: user.studentNo,
                isStaff: user.isStaff,
                token: 'fake-jwt-token'
            };

            let response = of (new HttpResponse({
                status: 200,
                body: body
            }));
            return handle(response);
        } else {
            // else return 400 bad request
            next.handle().catch((response: any) => {
                // ....
                // Do messaging and error handling here
                return throwError({
                    error: {
                        message: 'Email or password is incorrect'
                    }
                });
            });
        }
    }
}
于 2018-12-06T15:03:45.943 回答