Varun Sukheja
Varun Sukheja

Reputation: 6548

Angular - creating service to use google url shortener

I am trying to write a service for using google url shortener but facing problem Below is my service:

  urlShortener(longUrl: string): Observable<string> {
let body = {longUrl: longUrl}
let options = {
  params: {key: XXXXXX},
};
return this.http.post('https://www.googleapis.com/urlshortener/v1/url', body, options)
  .map(response => {
    console.debug('response',response);
    return response;
  })
  .catch(this.handleError);
}

Error from google API:

{
"error": {
 "errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}

}

There is no error on API key being used as the same code written in angular1 is returning shortUrl

Upvotes: 0

Views: 2678

Answers (2)

Varun Sukheja
Varun Sukheja

Reputation: 6548

After strugling for a day, solved it using http.request instead of using http.post Code is as follows:

let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let myParams = new URLSearchParams();
myParams.append('key', 'XXX-XXXX);

const options = new RequestOptions({
  method: RequestMethod.Post,
  headers: myHeaders,
  params: myParams,
  url: 'https://www.googleapis.com/urlshortener/v1/url',
  body: {longUrl: longUrl}
});
const req = new Request(options);

return this.http.request(req)
  .map(response => {
    console.debug('response', response.json().id);
    return response.json().id;
  })
  .catch(this.handleError);

Upvotes: 0

Rohit.007
Rohit.007

Reputation: 3502

Not Sure, but should provide the key in Authorization header.

Example:

let headers = new Headers();
    headers.append("Authorization","Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2");
    this.http.post(AUTHENTICATION_ENDPOINT, null, {headers: headers}).subscribe(response => {
      console.log(response);
    });

Upvotes: 0

Related Questions