Angular“值未定义”订阅映射的http响应(未发出请求?)

ock*_*888 3 javascript rxjs typescript angular

我有一个LoginComponent调用该submitLogin方法的简单登录表单组件 ( ) 。

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { first }  from 'rxjs/operators';

import { AuthenticationService } from '../../services';

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

    u = new FormControl('');
    p = new FormControl('');

    constructor(private route: ActivatedRoute, private router: Router, private auth: AuthenticationService) { }

    ngOnInit() {
        this.returnURL = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    submitLogin(): void {
        this.auth.login(this.u.value, this.p.value).pipe(first()).subscribe(
            r => {
                if (r) {
                    console.log("LoginComponent: r:", r);
                    this.router.navigate([this.returnURL]);
                }
            },
            error => {
                console.error("LoginComponent: Error:", error);
            }
        );
    }

}
Run Code Online (Sandbox Code Playgroud)

我得到的错误被打印为LoginComponent: Error: TypeError: 'values' is undefined,并且它被打印在该错误 lambda 中。

AuthenticationService外观(大致)是这样的:

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { User } from '../models/user';
import { APIService } from './api.service';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private http: HttpClient, private api: APIService) {
        this.currentUserSubject = new BehaviorSubject<User>(null);
        this.currentUser = this.currentUserSubject.asObservable();
    }
    login(u: string, p: string): Observable<boolean> {
        return this.api.login(u, p).pipe(map(
            r => {
                if (r && r.status === 200) {
                    this.updateCurrentUser();
                    console.log("returning true");
                    return true;
                }
                console.log("returning false");
                return false;
            }
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,map lambda 中的所有代码路径都返回一个布尔值。所以这张地图永远不应该吐出undefined值。顺便说一下,那些控制台日志永远不会发生。

我的 API 服务负责调用我正在运行的版本化 API。它有很多不相关的东西,但相关的部分是:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, first } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class APIService {
    public API_VERSION = '1.5';

    private cookies: string;

    constructor(private http: HttpClient) {}

    private do(method: string, path: string, data?: Object): Observable<HttpResponse<any>> {
        const options = {headers: new HttpHeaders({'Content-Type': 'application/json',
                                                   'Cookie': this.cookies}),
                         observe: 'response' as 'response',
                         body: data};
        return this.http.request(method, path, options).pipe(map(r => {
            //TODO pass alerts to the alert service
            let resp = r as HttpResponse<any>;
            if ('Cookie' in resp.headers) {
                this.cookies = resp.headers['Cookie']
            }
            console.log("returning resp");
            return resp;
        }));
    }

    public login(u, p): Observable<HttpResponse<any>> {
        const path = '/api/'+this.API_VERSION+'/user/login';
        return this.do('post', path, {u, p});
    }
}
Run Code Online (Sandbox Code Playgroud)

再次注意,map lambda 中的每个代码路径都返回一个值。另请注意,"returning resp"永远不会出现在控制台中。我也从未在网络面板中看到过 HTTP 请求。是什么赋予了?为什么它不执行请求,和/或可能导致此错误的原因是什么?

CGu*_*ach 5

复制您的代码后,我在控制台中获得的堆栈跟踪将我带到了 Angular 的 httpClient 模块 ( node_modules\@angular\common\esm5\http\src\headers.js)的标头代码中的“lazyInit”函数。

在函数的第二行,它遍历您提交的标头的值,您可以values在第三行看到变量。在那里它获取一个标题并访问它的值。接下来它将它转换为一个数组,如果它是一个字符串,然后检查它的长度——此时你会得到异常。

如果您查看您的 API 服务,您将提交两个标头:

'Content-Type': 'application/json',
'Cookie': this.cookies
Run Code Online (Sandbox Code Playgroud)

之前,您cookies像这样定义变量:

private cookies: string;

由于您没有分配值,它默认为undefined,这就是您的“Cookie”标头的值,它不是字符串,也没有length属性,因此它会抛出异常。

解决方案:

将 的初始定义更改cookies

private cookies = '';

解决了这个问题。