为什么Angular更改我的GET请求网址

时间:2018-07-12 17:47:36

标签: angular ionic-framework

当我在Angular中使用HttpClient服务时,我发现HttpClient更改了我的GET请求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});
  }
}



当我使用第一种方法时,REST api调用不起作用,并且我尝试在Chrome中(使用开发工具)查找为什么此方法不起作用。我发现Angular将我的GET请求URL更改为"http://localhost:8100/devices/states?id=3940649673951919,3940649673951920",但不应该是"https://api.objenious.com/v1/devices/states?id=3940649673951919,3940649673951920"吗?



当我尝试第二种方法时,一切正常。

1 个答案:

答案 0 :(得分:1)

您的代码如何知道将后端网址添加到路由路径的前缀。您错过了连接后端网址的机会。默认情况下,angular将您的应用程序URL视为主机,并将其余路径附加到该主机。这就是为什么您使用http://localhost:8100/...而不是api网址

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

getSystemStatesList(commaSeparatedSystemIds: string): Observable<any> {
    return this.http.get(this.objeniousRootUri +'/devices/states?id=3940649673951919,3940649673951920');
}