TypeError:无法使用业力读取空业力的属性“长度”

时间:2018-09-04 10:07:06

标签: angular typescript karma-jasmine karma-runner angular6

我已经看到很多有关此错误的问题,但是没有一个问题能帮助我找到问题的根源,如何知道该错误的来源以及如何解决呢?

TypeError: Cannot read property 'length' of null
at HttpHeaders.applyUpdate (webpack:///./node_modules/@angular/common/fesm5/http.js?:235:27)
at eval (webpack:///./node_modules/@angular/common/fesm5/http.js?:206:74)
at Array.forEach (<anonymous>)
at HttpHeaders.init (webpack:///./node_modules/@angular/common/fesm5/http.js?:206:33)
at HttpHeaders.forEach (webpack:///./node_modules/@angular/common/fesm5/http.js?:271:14)
at Observable.eval [as _subscribe] (webpack:///./node_modules/@angular/common/fesm5/http.js?:1481:25)
at Observable._trySubscribe (webpack:///./node_modules/rxjs/_esm5/internal/Observable.js?:48:25)
at Observable.subscribe (webpack:///./node_modules/rxjs/_esm5/internal/Observable.js?:34:22)
at eval (webpack:///./node_modules/rxjs/_esm5/internal/util/subscribeTo.js?:33:31)
at subscribeToResult (webpack:///./node_modules/rxjs/_esm5/internal/util/subscribeToResult.js?:10:84)
at ____________________Elapsed_26_ms__At__Tue_Sep_04_2018_11_58_19_GMT_0200__hora_de_verano_de_Europa_central_ (http://localhost)
at Object.onScheduleTask (webpack:///./node_modules/zone.js/dist/zone-testing.js?:107:22)
at ZoneDelegate.scheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:400:51)
at Object.onScheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:296:29)
at ZoneDelegate.scheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:400:51)
at Zone.scheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:231:43)
at Zone.scheduleMacroTask (webpack:///./node_modules/zone.js/dist/zone.js?:254:25)
at scheduleMacroTaskWithCurrentZone (webpack:///./node_modules/zone.js/dist/zone.js?:1113:25)
at eval (webpack:///./node_modules/zone.js/dist/zone.js?:2089:28)

在浏览器控制台(Chrome)和使用Karma启动测试时都可以看到该错误。

另一条失败的测试消息显示以下内容:

[object ErrorEvent] thrown

我也不知道如何跟踪此错误。

更新:最小,完整和可验证的示例

服务:

import { HttpClient } from '@angular/common/http';
import { Country } from '../countries/country.model';
import { Observable } from 'rxjs';
import { Configuration } from '../../constants';

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

    private server: String;

    constructor(
        private http: HttpClient,
        private configuration: Configuration
    ) {
        this.server = this.configuration.serverOCD;
    }

    getCountries(): Observable<Country[]> {
        return this.http.get<Country[]>(this.server + '/api/v1/country');
    }
}

组件:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

import { DropdownService } from '../services/dropdown.service';
import { Country } from './country.model';
import { Observable } from 'rxjs';

@Component({
    selector: 'dropdown-countries',
    templateUrl: './countries.component.html',
    styleUrls: ['./countries.component.css']
})

export class CountriesComponent implements OnInit {

    countries$: Observable<Country[]>;
    countries: Country[] = [];
    countriesForm: FormGroup;
    country: FormControl;

    constructor(
        private fb: FormBuilder,
        private dropdownService: DropdownService,
    ) { }

    ngOnInit() {
        this.countriesForm = this.fb.group({
            country: this.fb.control(new Country().code = '')
        });

        // 1st try
        this.getCountries();

        // 2nd try
        this.countries$ = this.dropdownService.getCountries();
    }

    getCountries() {
        this.dropdownService.getCountries().subscribe(
            data => this.countries = data,
            err => console.error(err),
            () => console.log('done loading countries')
        );
    }

}

模板:

<div [formGroup]="countriesForm">
    <select id="countriesDropdown" class="form-control form-control-sm" formControlName="country">
        <option value="" disabled>Choose a Country</option>
        <option *ngFor="let country of countries$ | async" [ngValue]="country">{{country.longDescription}}</option>
    </select>
</div>
<p>Form value: {{ countriesForm.value | json }}</p>

1 个答案:

答案 0 :(得分:0)

好吧,经过2天的研究,我设法找到了问题,并且它来自于我认为不会影响以下代码的代码:

GenericService:

@Injectable()
export class JWTInterceptor implements HttpInterceptor {

    private token: string;

    constructor(
        private config: Configuration,
        private authStore: AuthenticationStore
    ) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        this.token = this.authStore.getToken();

        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        req = req.clone({ headers: req.headers.set('Authorization', this.token) });

        return next.handle(req);
    }
}

SharedModule:

providers: [
    GenericService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JWTInterceptor,
      multi: true,
    }
],

有了这些代码片段,所有请求都被JWTInterceptor拦截了,它引发了错误并且我不想要,所以我使用HttpBackend忽略了该拦截器:

DropdownService:

constructor(
    private http: HttpClient,
    private handler: HttpBackend, // to ignore interceptor
    private configuration: Configuration
) {
    this.http = new HttpClient(this.handler); // use it in HttpClient
    this.server = this.configuration.serverOCD;
}