简体   繁体   English

Angular2中的路径参数

[英]Path parameters in Angular2

How are we meant to handle path parameters in Angular 2 when doing RESTful calls to a Web Service? 在对Web服务进行RESTful调用时,我们打算如何在Angular 2中处理路径参数?

I've found the URLSearchParams object for query parameters but from what I have found it seems we'll have to make do with string-concatenation for the path itself. 我已经找到了用于查询参数的URLSearchParams对象,但是从我发现的内容来看,我们似乎必须对路径本身进行字符串串联。 Like 喜欢

let url = 'api/v1/something/' + encodeURIComponent(someParameter) + 
          '/etc/' + encodeURIComponent(anotherParam) + '/and/so/on';

Is there, included in angular2, something that does similar to: 在angular2中是否包含类似以下内容的内容:

let url = new URL('api/v1/something/{id}/etc/{name}/and/so/on', param1, param2);

I can of course create something similar myself but prefer if there is something included in angular2. 我当然可以自己创建类似的东西,但是如果angular2中包含一些东西,我会更喜欢。

Indeed, you can use string interpolation and nearly exactly the same thing you suggest, assuming id and name are already set and encoded. 确实,您可以使用字符串插值和几乎完全相同的建议(假设idname已经设置和编码)。

let url = new URL(`api/v1/something/${id}/etc/${name}/and/so/on`);

I'll note that currently the ES6 URL class only supports searchParams , but has no notion of path parameters. 我会注意到,当前ES6 URL类仅支持searchParams ,但没有路径参数的概念。

Also, I know of no method that will automatically encode your parameters without implementing your own QueryEncoder with URLSearchParams 另外,我知道没有一种方法,它会自动编码您的参数,而实现的自己的QueryEncoderURLSearchParams

If anybody is interested, this is what I ended up doing: 如果有人感兴趣,这就是我最终要做的事情:

export interface PathParameters {
  [parameterName: string]: string;
}

export class Url {

  public static create(url: string, parameters: PathParameters) {
    const placeholders = url.match(/({[a-zA-Z]*})/g);
    placeholders.forEach((placeholder: string) => {
      const key = placeholder.substr(1, placeholder.length - 2);
      const value = parameters[key];
      if (!value) {
        throw new Error(`parameter ${key} was not provided`);
      }
      url = url.replace(placeholder, encodeURIComponent(value));
    });
    return url;
  }

}

How to use: 如何使用:

const url = Url.create('/api/cars/{carId}/parts/{partId}', {
    carId: carId,
    partId: partId
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM