HttpInterceptor和内存数据服务Angular 7

时间:2018-12-06 14:48:08

标签: angular observable angular-in-memory-web-api

我一直在为正在使用的应用程序使用虚拟身份验证。因此,我已经使用虚拟本地用户成功实现了此操作。

不幸的是,在尝试使其与内存数据服务一起使用时,我遇到了麻烦。我的用户数组返回未定义状态,并且无法在控制台日志中将错误更改为字符串。 下面是使用拦截器的伪造后端。

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:超出最大调用堆栈大小

1 个答案:

答案 0 :(得分:0)

通过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'
                    }
                });
            });
        }
    }
}