开发者问题收集

Angular 5 - 添加标题时出现的问题

2018-03-23
2095

我有这个...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 选项,这工作完美。

有什么线索吗?

2个回答

尝试使用 @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);
  }             
}
Amol Bhor
2018-03-23

我也有同样的问题。我认为关键在于您的 HttpHeaders。

this.gs.token 可能为空,因此会带来错误。

试试这个:

const httpOptions = {
headers: new HttpHeaders({
  'Authorization': this.gs.token + ''
})

};

gus
2018-05-11