angulargoogle-url-shortener

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


Solution

  • 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);