url在@ angular / http中嵌入了参数

时间:2016-12-17 01:17:12

标签: rest http angular typescript parameters

我使用后端以?-notation和url-embedded方式接收搜索查询参数。我知道我可以使用例如URLSearchParams / RequestOptionsArgs发出请求,例如到http://mydomain/api/card?id=abc

但是我怎么能使用例如像http://mydomain/api/card/abc这样的mor RESTish来定义像'card /:id'这样的url,例如在定义应用程序路由时也会这样做?

以下snipplet就是我现在如何建立一个get请求:

public getRequest(url: string, params: URLSearchParams): Observable < Response > {
  let options: RequestOptionsArgs = {
    url: url,
    method: RequestMethod.Get,
    headers: RestService.createHeaders(),
    search: params,
    responseType: ResponseContentType.Json
  };

  let request: any = this.http.get(url, options);
  return request.map((res: any) => {
    let response = new ServerResponse(res);
    if (response.status == ServerResponseStatus.OK) return response.data;
    else console.log('ERROR: GET request ' + options + ' resulted in status:' + response.status);
  });
  //.catch(this.handleError);
}

2 个答案:

答案 0 :(得分:0)

你只需要以你想要支持的格式传递url,所以只需将URL传入你的函数,看起来更像你想要的REST URL。

然后您只需要更改后端即可了解新的URL。您没有说明您在后端使用的技术。如果您正在使用NodeJS,那么我建议使用expressJS,它非常适合使用/:id表示法处理URL参数和路由

答案 1 :(得分:0)

card/:id是一种语法,表示:id将被替换为任何数字或字符串。因此,假设您在替换后请求http://mydomain/api/card/abc这里abc :id是您 let myid='abc'; `let url='http://mydomain/api/card/'+this.myid;` <- here id is a variable which you get as a argument. let request: any = this.http.get(url, options); return request.map((res: any) => { let response = new ServerResponse(res); if (response.status == ServerResponseStatus.OK) return response.data; else console.log('ERROR: GET request ' + options + ' resulted in status:' + response.status); }); //.catch(this.handleError); } 不断变化的部分。

你可以这么做。

private static final char CL = getRandomCapitalLetter(),  ML = getRandomMinusculeLetter(),
         NC = getRandomNumericCharacter(), SC = getRandomSpecialCharacter();