1

When I use HttpClient service in Angular, I found that HttpClient changed my GET request URL.

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";

const objeniousApiKey = '...';
const objeniousRootUri = 'https://api.objenious.com/v1';

@Injectable()
export class ObjeniousRestProvider {

  constructor(public http: HttpClient) {
  }

  get(route: string, params?: HttpParams, headers ?: HttpHeaders): Observable<any> {
    if (!headers) {
      headers = new HttpHeaders();
    }

    headers = headers.set('apiKey', objeniousApiKey);

    return this.http.get(objeniousRootUri + route, {headers, params});
  }


  getSystemStatesList(commaSeparatedSystemIds: string): Observable<any> {
// This does not work  (first method)
    return this.http.get(`/devices/states?id=3940649673951919,3940649673951920`);


// This works  (second method)
    // let headers = new HttpHeaders().set('apiKey', objeniousApiKey);
    // return this.http.get('https://api.objenious.com/v1/devices/states?id=3940649673951919,3940649673951920', {headers});
  }
}



When I use the first method, the REST api call does not work, and I try to find in Chrome (using dev tools) why this is not working. I found that Angular changed my GET request URL to "http://localhost:8100/devices/states?id=3940649673951919,3940649673951920", but shouldn't it be "https://api.objenious.com/v1/devices/states?id=3940649673951919,3940649673951920" ?



When I tried the second method, everything just works fine.

1 Answer 1

1

How does your code know to prefix your backend url to route path. You have missed to concat your backend url. By default, angular considers your application url as the host and attaches the remaining path to it. That is why you have http://localhost:8100/... instead of api url

const objeniousRootUri = 'https://api.objenious.com/v1';

getSystemStatesList(commaSeparatedSystemIds: string): Observable<any> {
    return this.http.get(this.objeniousRootUri +'/devices/states?id=3940649673951919,3940649673951920');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.