我是打字稿和angular的新手,我有一个像下面的课
import { Component, OnInit } from '@angular/core';
import { User } from '../domain/User';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { LoginResponse } from '../domain/LoginResponse'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
private user:User = new User();
private xSSOFamilyId:string = 'BOMO';
constructor(private httpClient: HttpClient) { }
ngOnInit() {
}
login(): void {
var authorization:string = 'Basic ' + btoa(this.user.cwopa + ":" + this.user.password);
var headers = {};
headers['Authorization'] = authorization;
headers['userId'] = this.user.cwopa; // this line is throwing error
headers['X-SSO-Family-Id'] = this.xSSOFamilyId; // this line is throwing error.
var httpHeaders = new HttpHeaders(headers);
this.httpClient.post<LoginResponse>('http://localhost:8081/web-beginner/authenticate.json', {}, {headers: httpHeaders}).subscribe(data => {
console.log(data.apiKey);
}, error => {
console.log("error occured");
});
}
}
运行上面的代码时,出现以下错误
错误TypeError:无法读取未定义的属性“ length” 在评估时(http.js:123) 在Array.forEach() 在HttpHeaders.lazyInit(http.js:117) 在HttpHeaders.init(http.js:265) 在HttpHeaders.forEach(http.js:368) 在Observable.eval [作为_subscribe](http.js:2170) 在Observable._trySubscribe(Observable.js:172) 在Observable.subscribe(Observable.js:160) 在subscribeToResult(subscribeToResult.js:23) 在MergeMapSubscriber._innerSub(mergeMap.js:138)
但是,当我尝试设置headers ['userId'] ='krishna'和headers ['X-SSO-Family-Id'] ='BOMO'的值时,代码有效。
然后我尝试将代码更改为
import { Component, OnInit } from '@angular/core';
import { User } from '../domain/User';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { LoginResponse } from '../domain/LoginResponse'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
private user:User = new User();
private xSSOFamilyId:string = 'BOMO';
constructor(private httpClient: HttpClient) { }
ngOnInit() {
}
login(): void {
var authorization:string = 'Basic ' + btoa(this.user.cwopa + ":" + this.user.password);
var userId:string = this.user.cwopa;
var xSSOFamilyId:string = this.xSSOFamilyId;
var headers = {};
headers['Authorization'] = authorization;
headers['userId'] = userId;
headers['X-SSO-Family-Id'] = xSSOFamilyId;
var httpHeaders = new HttpHeaders(headers);
this.httpClient.post<LoginResponse>('http://localhost:8081/web-beginner/authenticate.json', {}, {headers: httpHeaders}).subscribe(data => {
console.log(data.apiKey);
}, error => {
console.log("error occured");
});
}
}
它再次失败,并显示相同的错误。
我想知道为什么headers['Authorization'] = authorization;
不能正常工作,而headers['userId'] = userId;
和headers['X-SSO-Family-Id'] = xSSOFamilyId;
为什么不能正常工作。
有人可以帮助我吗?