Reputation: 12538
I am trying to build an app that connects to the twitter api. To accomplish this, I need to send a http get request with a set of headers using Angular2.
Note, the below curl requests is successful (assuming the correct keys are in place).
This is what I tried, the only issue is, with the below implementation, I am an unable to pass in the necessary headers.
Was wondering if anybody has encountered this and has any suggestions on how to resolve?
Thanks in advance
constructor(private _http: Http) {
}
getTwitterResponse() {
return this._http.get('https://api.twitter.com/1.1/statuses/home_timeline.json')
.map(res => res.text);
}
Curl Request Sample w/ Headers (w/ auth keys removed)
curl --get 'https://api.twitter.com/1.1/statuses/home_timeline.json' --header 'Authorization: OAuth oauth_consumer_key="123456", oauth_nonce="123456", oauth_signature="f%123456%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1475158916", oauth_token="123456", oauth_version="1.0"' --verbose
Upvotes: 1
Views: 963
Reputation: 50633
You add headers to your request like this:
import { Headers, RequestOptions } from '@angular/http';
getTwitterResponse() {
let headers = new Headers({ "Content-Type": "application/json" });
let options = new RequestOptions({ headers: headers });
let url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
return this._http.get(url, options).map(res => res.text);
}
Explanation of what's happening here: request get
of Http
have the following signature:
get(url: string, options?: RequestOptionsArgs)
Second argument is optional and it's type is RequestOptionsArgs
which is an interface used to construct RequestOptions
, which means you can pass RequestOptions
to get
as a second argument. RequestOptionsArgs
is an interface with following attributes:
export interface RequestOptionsArgs {
url?: string;
method?: string | RequestMethod;
search?: string | URLSearchParams;
headers?: Headers;
body?: any;
withCredentials?: boolean;
responseType?: ResponseContentType;
}
All attributes are optional and that's why we can pass only headers
to our options
. You can change Content-Type
with anything you want and you can add more than 1 header:
headers: Headers = new Headers({
'First header': 'First value',
'Second header': 'Second value',
'Third header': 'Third value',
'Fourth header': 'Fourth value'
});
You can read more about everything I just blabbed about on the following links:
Upvotes: 2