Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - Angular 4 get headers from API response

I'm sending a request to an API, it returns an array of data, but I don't know how to extract the headers from that url, this is what i've tried in my service

@Injectable()
export class ResourcesService {
private resourcesurl = "http://localhost:9111/v1/resources";

constructor(private http: Http) { }

getResources() {
  let headers = new Headers();
  headers.append("api_key", "123456");
  return this.http.get(this.resourcesurl, { headers: headers 
 }).map(this.extractData).catch(this.handleError);
}
getresourceheaders(){
  let headers = new Headers();
  headers.append("api_key", "123456");
  let options = new RequestOptions();
  let testsss = options.headers
  let headerapi = this.http.request(this.resourcesurl, options);
  let test = this.http.get(this.resourcesurl, { headers: headers });
  console.log(headerapi);
}
private extractData(res: Response) {
  let body = res.json();
  return body.data || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
  const body = error.json() || '';
  const err = body.error || JSON.stringify(body);
  errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
  errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
 }
}

I want to get the headers from that response that in this case is resourceurl

any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Clear angular 5 answer

By default, this.http.whatever's returned observable will be on the data returned, not the HttpResponse.

If you have a peak at: https://angular.io/api/common/http/HttpClient You'll notice the options take an "observe" parameter of a HttpObserve type. While it's not documented what the HttpObserve is, if you put it as "response" then you will instead receive an instance of HttpResponse<T>(https://angular.io/api/common/http/HttpResponse)

So, here's an example request:

this.http.get(url, {observe: 'response'})
    .subscribe(resp => console.log(resp.headers))

Note: Due to browser cors security, you will not be-able to see headers unless the API provides Access-Control-Expose-Headers: with your custom headers if your api and angular app do not have the same domain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...