W3cubDocs

/Angular 12

Location

class final

A service that applications can use to interact with a browser's URL.

See more...

class Location {
  static normalizeQueryParams: (params: string) => string
  static joinWithSlash: (start: string, end: string) => string
  static stripTrailingSlash: (url: string) => string
  path(includeHash: boolean = false): string
  getState(): unknown
  isCurrentPathEqualTo(path: string, query: string = ''): boolean
  normalize(url: string): string
  prepareExternalUrl(url: string): string
  go(path: string, query: string = '', state: any = null): void
  replaceState(path: string, query: string = '', state: any = null): void
  forward(): void
  back(): void
  historyGo(relativePosition: number = 0): void
  onUrlChange(fn: (url: string, state: unknown) => void)
  subscribe(onNext: (value: PopStateEvent) => void, onThrow?: (exception: any) => void, onReturn?: () => void): SubscriptionLike
}

Subclasses

Provided in

Description

Depending on the LocationStrategy used, Location persists to the URL's path or the URL's hash segment.

Further information is available in the Usage Notes...

Static properties

Property Description
static normalizeQueryParams: (params: string) => string

Normalizes URL parameters by prepending with ? if needed.

static joinWithSlash: (start: string, end: string) => string

Joins two parts of a URL with a slash if needed.

static stripTrailingSlash: (url: string) => string

Removes a trailing slash from a URL string if needed. Looks for the first occurrence of either #, ?, or the end of the line as / characters and removes the trailing slash if one exists.

Methods

Normalizes the URL path for this location.

path(includeHash: boolean = false): string

Parameters
includeHash boolean

True to include an anchor fragment in the path.

Optional. Default is false.

Returns

string: The normalized URL path.

Reports the current state of the location history.

getState(): unknown

Parameters

There are no parameters.

Returns

unknown: The current value of the history.state object.

Normalizes the given path and compares to the current normalized path.

isCurrentPathEqualTo(path: string, query: string = ''): boolean

Parameters
path string

The given URL path.

query string

Query parameters.

Optional. Default is ''.

Returns

boolean: True if the given URL path is equal to the current normalized path, false otherwise.

Normalizes a URL path by stripping any trailing slashes.

normalize(url: string): string

Parameters
url string

String representing a URL.

Returns

string: The normalized URL string.

Normalizes an external URL path. If the given URL doesn't begin with a leading slash ('/'), adds one before normalizing. Adds a hash if HashLocationStrategy is in use, or the APP_BASE_HREF if the PathLocationStrategy is in use.

prepareExternalUrl(url: string): string

Parameters
url string

String representing a URL.

Returns

string: A normalized platform-specific URL.

Changes the browser's URL to a normalized version of a given URL, and pushes a new item onto the platform's history.

go(path: string, query: string = '', state: any = null): void

Parameters
path string

URL path to normalize.

query string

Query parameters.

Optional. Default is ''.

state any

Location history state.

Optional. Default is null.

Returns

void

Changes the browser's URL to a normalized version of the given URL, and replaces the top item on the platform's history stack.

replaceState(path: string, query: string = '', state: any = null): void

Parameters
path string

URL path to normalize.

query string

Query parameters.

Optional. Default is ''.

state any

Location history state.

Optional. Default is null.

Returns

void

Navigates forward in the platform's history.

forward(): void

Parameters

There are no parameters.

Returns

void

Navigates back in the platform's history.

back(): void

Parameters

There are no parameters.

Returns

void

Navigate to a specific page from session history, identified by its relative position to the current page.

See also:

historyGo(relativePosition: number = 0): void

Parameters
relativePosition number

Position of the target page in the history relative to the current page. A negative value moves backwards, a positive value moves forwards, e.g. location.historyGo(2) moves forward two pages and location.historyGo(-2) moves back two pages. When we try to go beyond what's stored in the history session, we stay in the current page. Same behaviour occurs when relativePosition equals 0.

Optional. Default is 0.

Returns

void

Registers a URL change listener. Use to catch updates performed by the Angular framework that are not detectible through "popstate" or "hashchange" events.

onUrlChange(fn: (url: string, state: unknown) => void)

Parameters
fn (url: string, state: unknown) => void

The change handler function, which take a URL and a location history state.

Subscribes to the platform's popState events.

See also:

subscribe(onNext: (value: PopStateEvent) => void, onThrow?: (exception: any) => void, onReturn?: () => void): SubscriptionLike

Parameters
onNext (value: PopStateEvent) => void
onThrow (exception: any) => void

Optional. Default is undefined.

onReturn () => void

Optional. Default is undefined.

Returns

SubscriptionLike: Subscribed events.

Note: Location.go() does not trigger the popState event in the browser. Use Location.onUrlChange() to subscribe to URL changes instead.

Usage notes

It's better to use the Router.navigate() service to trigger route changes. Use Location only if you need to interact with or create normalized URLs outside of routing.

Location is responsible for normalizing the URL against the application's base href. A normalized URL is absolute from the URL host, includes the application's base href, and has no trailing slash:

  • /my/app/user/123 is normalized
  • my/app/user/123 is not normalized
  • /my/app/user/123/ is not normalized

Example

import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import {Component} from '@angular/core';

@Component({
  selector: 'path-location',
  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],
  template: `
    <h1>PathLocationStrategy</h1>
    Current URL is: <code>{{location.path()}}</code><br>
    Normalize: <code>/foo/bar/</code> is: <code>{{location.normalize('foo/bar')}}</code><br>
  `
})
export class PathLocationComponent {
  location: Location;
  constructor(location: Location) {
    this.location = location;
  }
}

© 2010–2021 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v12.angular.io/api/common/Location