Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat(Location): add search() method which returns an Object #4905

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions modules/angular2/src/core/facade/decode.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
library angular2.src.core.facade.decode;

import 'dart:core' show String, Uri;

String tryDecodeURIComponent(String encodedComponent) {
try {
return Uri.decodeComponent(encodedComponent);
} catch(exception, stackTrace) {
// Ignore any invalid uri component
}
}
10 changes: 10 additions & 0 deletions modules/angular2/src/core/facade/decode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Tries to decode the URI component without throwing an exception.
*/
export function tryDecodeURIComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component
}
}
2 changes: 2 additions & 0 deletions modules/angular2/src/mock/location_mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export class SpyLocation implements Location {

path(): string { return this._path; }

search(): any { return this._query; }

simulateUrlPop(pathname: string) {
ObservableWrapper.callEmit(this._subject, {'url': pathname, 'pop': true});
}
Expand Down
7 changes: 6 additions & 1 deletion modules/angular2/src/mock/mock_location_strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {LocationStrategy} from 'angular2/src/router/location_strategy';
export class MockLocationStrategy extends LocationStrategy {
internalBaseHref: string = '/';
internalPath: string = '/';
internalSearch: string = '';
internalTitle: string = '';
urlChanges: string[] = [];
/** @internal */
Expand All @@ -24,6 +25,8 @@ export class MockLocationStrategy extends LocationStrategy {

path(): string { return this.internalPath; }

search(): any { return this.internalSearch; }

prepareExternalUrl(internal: string): string {
if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) {
return this.internalBaseHref + internal.substring(1);
Expand All @@ -34,8 +37,10 @@ export class MockLocationStrategy extends LocationStrategy {
pushState(ctx: any, title: string, path: string, query: string): void {
this.internalTitle = title;

var url = path + (query.length > 0 ? ('?' + query) : '');
query = query.length > 0 ? ('?' + query) : '';
var url = path + query;
this.internalPath = url;
this.internalSearch = query;

var externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push(externalUrl);
Expand Down
2 changes: 2 additions & 0 deletions modules/angular2/src/router/hash_location_strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export class HashLocationStrategy extends LocationStrategy {
normalizeQueryParams(this._platformLocation.search);
}

search(): string { return this._platformLocation.search; }

prepareExternalUrl(internal: string): string {
var url = joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('#' + url) : url;
Expand Down
43 changes: 43 additions & 0 deletions modules/angular2/src/router/location.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {LocationStrategy} from './location_strategy';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {Injectable, Inject} from 'angular2/core';
import {StringWrapper, RegExpWrapper, isPresent, isArray} from 'angular2/src/facade/lang';
import {tryDecodeURIComponent} from 'angular2/src/core/facade/decode';

/**
* `Location` is a service that applications can use to interact with a browser's URL.
Expand Down Expand Up @@ -62,6 +64,19 @@ export class Location {
*/
path(): string { return this.normalize(this.platformStrategy.path()); }

/**
* Returns query params as an object.
*/
search(): any {
// the search value is always prefixed with a `?`
let search = this.platformStrategy.search();

// Dart will complain if a call to substring is
// executed with a position value that extends the
// length of string.
return (search.length > 0 ? parseKeyValue(search.substring(1)) : {});
}

/**
* Given a string representing a URL, returns the normalized URL path without leading or
* trailing slashes
Expand Down Expand Up @@ -140,3 +155,31 @@ function stripTrailingSlash(url: string): string {
}
return url;
}

/**
* Parses an escaped url query string into key-value pairs.
*/
function parseKeyValue(keyValue: string = ""): any {
let obj: any = {};
let pairs: Array<string> = keyValue.split('&');
for (let i = 0; i < pairs.length; i++) {
let key: string;
let val: string;
let kv: string = pairs[i];
let parts: Array<string>;
if (isPresent(kv)) {
key = kv = StringWrapper.replaceAll(kv, /\+/g, '%20');
parts = kv.split('=');
if (parts.length === 2) {
key = parts[0];
val = parts[1];
}
key = tryDecodeURIComponent(key);
if (isPresent(key)) {
val = isPresent(val) ? tryDecodeURIComponent(val) : '';
obj[key] = val;
}
}
}
return obj;
}
1 change: 1 addition & 0 deletions modules/angular2/src/router/location_strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {OpaqueToken} from 'angular2/core';
export abstract class LocationStrategy {
abstract path(): string;
abstract prepareExternalUrl(internal: string): string;
abstract search(): any;
abstract pushState(state: any, title: string, url: string, queryParams: string): void;
abstract replaceState(state: any, title: string, url: string, queryParams: string): void;
abstract forward(): void;
Expand Down
2 changes: 2 additions & 0 deletions modules/angular2/src/router/path_location_strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ export class PathLocationStrategy extends LocationStrategy {
return this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search);
}

search(): string { return this._platformLocation.search; }

pushState(state: any, title: string, url: string, queryParams: string) {
var externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl);
Expand Down
19 changes: 19 additions & 0 deletions modules/angular2/test/router/location_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,24 @@ export function main() {
location.go('/home', "key=value");
expect(location.path()).toEqual("/home?key=value");
});

it('should provide query params as an Object', () => {
var locationStrategy = new MockLocationStrategy();
var location = new Location(locationStrategy);

location.go('/home', "key=value");
expect(location.search()['key']).toEqual("value");

// should parse various formats cleanly
location.go('/home', "opinion=angular+is+awesome!");
expect(location.search()['opinion']).toEqual("angular is awesome!");

location.go(
'/home',
"opinion=Jeff+Cross is good as a worldwide news+reporter&random=other:formatting");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

expect(location.search()['opinion'])
.toEqual("Jeff Cross is good as a worldwide news reporter");
expect(location.search()['random']).toEqual("other:formatting");
});
});
}