ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined in Angular 7 and rxjx

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined in Angular 7 and rxjx

我最近将我的 angular 2 应用程序升级到 angular 7。我遇到的挑战之一是 user.service.ts 我有 isAuthentiated 方法。基本上,这个方法被传递到 auth.guard.ts 中,这样我就可以在用户名不在我的列表中时指导他们。

用户服务检索用户,然后 isAuthenticated 检查用户。 Auth guard 正在检查用户。如果用户在列表中,则授予访问权限,否则将他们导航到某个网站。

user.service.ts

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

@Injectable()
export class UserService {
    baseUrl = environment.apiUrl;

    constructor(private http: HttpClient) { }

    private extractData(res: Response) {
        const body = res;
        return body || { };
    }

    ... other methods

    isAuthenticated(): Observable<boolean> {
        return this.http.get(this.baseUrl + 'users').pipe(
            map(this.extractData),
            map(res => !!res.length)
        );
    }
}

我的 auth.guard.ts 是:

import { UserService } from './../_services/user.service';
import { Injectable } from '@angular/core';
import { CanActivate, RouterStateSnapshot, Router } from '@angular/router';
import { AlertifyService } from '../_services/alertify.service';
import { map } from 'rxjs/operators';


@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private userService: UserService,
    private alertifyService: AlertifyService,
    private router: Router
  ) {}

  canActivate(route, state: RouterStateSnapshot) {
    return this.userService.isAuthenticated().pipe(map(user => {
      if (!user) {
        return true;
      } else {
        this.router.navigate(['/authentication/get-jhed']);
        this.alertifyService.error('You need to be authenticated to access this area');
        return false;
      }
    }));
  }
}

此代码returns出现以下错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined

我试过了 res[0].length 我没有收到错误,但这次什么也没发生。

我可以使用 Http 解决这个问题,如下所示:

isAuthenticated(): Observable<boolean> {
    return this.http.get(this.baseUrl + 'users').pipe(
        map(res => res.json()),
        map(res => !!res.length)
    );
}

请注意,我在这里使用 Http,而不是 HttpClient

如有任何帮助,我们将不胜感激!

HttpClient 默认表示响应主体不是整个响应对象。如果您同时从 Http 迁移到 HttpClient - 为了与以前的方式兼容 - 使用选项对象 return 回调中的整个响应。

isAuthenticated(): Observable<boolean> {
    return this.http.get(this.baseUrl + 'users', { observe: 'response' }).pipe(
        map(this.extractData),
        map(res => !!res.length)
    );
}