简体   繁体   中英

Path parameters in Angular2

How are we meant to handle path parameters in Angular 2 when doing RESTful calls to a Web Service?

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. Like

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

Is there, included in angular2, something that does similar to:

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.

Indeed, you can use string interpolation and nearly exactly the same thing you suggest, assuming id and name are already set and encoded.

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.

Also, I know of no method that will automatically encode your parameters without implementing your own QueryEncoder with URLSearchParams

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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