我有这个... myservice.service.ts:
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ReqLogin, ResLogin, ResList} from '../../interfaces/general';
import { GlobalService} from '../global/global.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
...
list(): Observable<ResList> {
const url = this.gs.backendServer + this.gs.backend.endpoints.list;
const httpOptions = {
headers: new HttpHeaders({
'Authorization': this.gs.token
})
};
return this.http.get(url, httpOptions)
.map(res => <ResList> res)
.do(dataReceived => console.log(dataReceived));
}
这很好用,服务器接收阅读器,我从服务器接收数据,但我也收到这个例外:
ERROR TypeError: Cannot read property 'length' of undefined
at eval (http.js:123)
at Array.forEach (<anonymous>)
at HttpHeaders.lazyInit (http.js:117)
at HttpHeaders.init (http.js:265)
at HttpHeaders.forEach (http.js:368)
at Observable.eval [as _subscribe] (http.js:2172)
at Observable._trySubscribe (Observable.js:172)
at Observable.subscribe (Observable.js:160)
at subscribeToResult (subscribeToResult.js:23)
at MergeMapSubscriber._innerSub (mergeMap.js:138)
如果我放弃Http选项,这就完美了。
任何线索?
答案 0 :(得分:0)
使用@ angular / http库中的Headers和RequestOptions尝试此操作。
ApplicationService.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
@Injectable()
export class ApplicationService {
constructor(private http: Http) {
}
myformPost(id:number, formData : any){
let header = this.initHeaders();
let options = new RequestOptions({ headers: header, method: 'post'});
let body = JSON.stringify(formData);
return this.http.post(this.myapiUrl, body, options)
.map(res => {
return res.json();
})
.catch(this.handleError.bind(this));
}
private initHeaders(): Headers {
var headers = new Headers();
let token = localstorage.getItem(StorageKey.USER_TOKEN);
if (token !== null) {
headers.append('Authorization', token);
}
headers.append('Pragma', 'no-cache');
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
return headers;
}
private handleError(error: any): Observable<any> {
return Observable.throw(error.message || error);
}
}