Angular TypeError:无法读取属性';长度';使用业力来消除无业力
我看到了很多关于这个错误的问题,但没有一个能帮助我找到问题的根源,我如何知道这个错误来自何处,如何修复它Angular TypeError:无法读取属性';长度';使用业力来消除无业力,angular,typescript,karma-jasmine,karma-runner,angular6,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/fesm
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)
我也不知道如何追踪这个错误
更新:最小、完整且可验证的示例
服务:
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');
}
}
从'@angular/common/http'导入{HttpClient};
从“../countries/Country.model”导入{Country};
从“rxjs”导入{Observable};
从“../../constants”导入{Configuration};
@注射的({
providedIn:'根'
})
导出类DropdownService{
私有服务器:字符串;
建造师(
私有http:HttpClient,
私有配置:配置
) {
this.server=this.configuration.serverOCD;
}
getCountries():可观察{
返回this.http.get(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')
);
}
}
从'@angular/core'导入{Component,OnInit};
从'@angular/forms'导入{FormGroup,FormBuilder,FormControl};
从“../services/dropdown.service”导入{DropdownService};
从“/Country.model”导入{Country};
从“rxjs”导入{Observable};
@组成部分({
选择器:'下拉列表国家',
templateUrl:“./countries.component.html”,
样式URL:['./countries.component.css']
})
导出类Countries组件实现OnInit{
国家:可见;
国家:国家[]=[];
国家形式:FormGroup;
国家:FormControl;
建造师(
私人fb:FormBuilder,
私人dropdownService:dropdownService,
) { }
恩戈尼尼特(){
this.countriesForm=this.fb.group({
国家/地区:this.fb.control(新国家/地区().code='')
});
//第一次尝试
这个。getCountries();
//第二次尝试
this.countries$=this.dropdownService.getCountries();
}
getCountries(){
这个.dropdownService.getCountries().subscribe(
data=>this.countries=数据,
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>
选择一个国家
{{country.longDescription}
表单值:{{countriesForm.value | json}
好吧,经过两天的研究,我终于找到了问题所在,它来自于我认为不会影响的代码:
一般服务:
@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);
}
}
有了这些代码片段,所有请求都被JWTInterceptor截获,它抛出了错误,我不想看到,所以我使用HttpBackend
忽略了该截获器:
下拉服务:
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;
}
我们需要一个或一些上下文来帮助您。
getCountries()
是异步的,因此如果您在某处检查this.countries.length
,请使用空数组将其初始化为默认值,或者检查this.countries
是否实际可用。我不认为你展示的代码真的有缺陷itself@Icepickle我没有在任何地方检查国家/地区的长度,我肯定遗漏了什么,是否有必要为此请求设置标题?
providers: [
GenericService,
{
provide: HTTP_INTERCEPTORS,
useClass: JWTInterceptor,
multi: true,
}
],
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;
}