@uirouter/core
- Version 6.1.1
- Published
- 4.61 MB
- No dependencies
- MIT license
Install
npm i @uirouter/core
yarn add @uirouter/core
pnpm add @uirouter/core
Overview
UI-Router Core: Framework agnostic, State-based routing for JavaScript Single Page Apps
Index
Variables
Functions
- all()
- allTrueR()
- ancestors()
- and()
- any()
- anyTrueR()
- applyPairs()
- arrayTuples()
- assertFn()
- assertMap()
- assertPredicate()
- beforeAfterSubstr()
- buildUrl()
- compose()
- copy()
- createProxyFunctions()
- curry()
- defaults()
- deregAll()
- eq()
- filter()
- find()
- flatten()
- flattenR()
- fnToString()
- functionToString()
- getParams()
- hashLocationPlugin()
- identity()
- inherit()
- invoke()
- is()
- isArray()
- isDate()
- isFunction()
- isInjectable()
- isNull()
- isNumber()
- isObject()
- isPromise()
- isRegExp()
- isString()
- isUndefined()
- joinNeighborsR()
- kebobString()
- keyValsToObjectR()
- locationPluginFactory()
- makeEvent()
- makeStub()
- map()
- mapObj()
- maxLength()
- memoryLocationPlugin()
- mergeR()
- noop()
- not()
- omit()
- or()
- padString()
- pairs()
- parse()
- parseUrl()
- pattern()
- pick()
- pipe()
- pluck()
- prop()
- pushR()
- pushStateLocationPlugin()
- resolvablesBuilder()
- servicesPlugin()
- silenceUncaughtInPromise()
- silentRejection()
- splitEqual()
- splitHash()
- splitOnDelim()
- splitQuery()
- stringify()
- stripLastPathElement()
- tail()
- trimHashVal()
- uniqR()
- unnest()
- unnestR()
- val()
- values()
Classes
Transition
- $id
- abort()
- addResolvable()
- dynamic()
- entering()
- error()
- exiting()
- from()
- getResolveTokens()
- ignored()
- injector()
- is()
- isActive
- onEnter()
- onError()
- onExit()
- onFinish()
- onRetain()
- onStart()
- onSuccess()
- options()
- originalTransition()
- params()
- paramsChanged()
- promise
- redirectedFrom()
- retained()
- router
- success
- targetState()
- to()
- toString()
- treeChanges()
- valid()
- views()
Interfaces
Enums
Type Aliases
Variables
variable $injector
const $injector: $InjectorLike;
A basic angular1-like injector api
This object implements four methods similar to the [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector)
UI-Router evolved from an angular 1 library to a framework agnostic library. However, some of the
@uirouter/core
code uses these ng1 style APIs to support ng1 style dependency injection.This object provides a naive implementation of a globally scoped dependency injection system. It supports the following DI approaches:
### Function parameter names
A function's
.toString()
is called, and the parameter names are parsed. This only works when the parameter names aren't "mangled" by a minifier such as UglifyJS.function injectedFunction(FooService, BarService) {// FooService and BarService are injected}### Function annotation
A function may be annotated with an array of dependency names as the
$inject
property.injectedFunction.$inject = [ 'FooService', 'BarService' ];function injectedFunction(fs, bs) {// FooService and BarService are injected as fs and bs parameters}### Array notation
An array provides the names of the dependencies to inject (as strings). The function is the last element of the array.
[ 'FooService', 'BarService', function (fs, bs) {// FooService and BarService are injected as fs and bs parameters}]{$InjectorLike}
variable $q
const $q: $QLike;
An angular1-like promise api
This object implements four methods similar to the [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q)
UI-Router evolved from an angular 1 library to a framework agnostic library. However, some of the
@uirouter/core
code uses these ng1 style APIs to support ng1 style dependency injection.This API provides native ES6 promise support wrapped as a $q-like API. Internally, UI-Router uses this $q object to perform promise operations. The
angular-ui-router
(ui-router for angular 1) uses the $q API provided by angular.$q-like promise api
variable defaultResolvePolicy
let defaultResolvePolicy: ResolvePolicy;
variable defaultTransOpts
let defaultTransOpts: TransitionOptions;
The default [[Transition]] options.
Include this object when applying custom defaults: let reloadOpts = { reload: true, notify: true } let options = defaults(theirOpts, customDefaults, defaultOptions);
variable equals
const equals: any;
variable extend
const extend: (toObj: Obj, ...fromObjs: Obj[]) => any;
variable forEach
const forEach: any;
variable fromJson
const fromJson: any;
variable hostRegex
const hostRegex: RegExp;
variable inArray
const inArray: { (array: any[], obj: any): boolean; (array: any[]): (obj: any) => boolean;};
Given an array, returns true if the object is found in the array, (using indexOf)
variable isDefined
const isDefined: Predicate<any>;
variable isNullOrUndefined
const isNullOrUndefined: Predicate<any>;
variable NATIVE_INJECTOR_TOKEN
const NATIVE_INJECTOR_TOKEN: string;
variable propEq
const propEq: Function;
Given a property name and a value, returns a function that returns a boolean based on whether the passed object has a property that matches the value let obj = { foo: 1, name: "blarg" }; let getName = propEq("name", "blarg"); getName(obj) === true
variable pushTo
const pushTo: { <T>(arr: T[], val: T): T; <T>(arr: T[]): (val: T) => T };
pushes a values to an array and returns the value
variable removeFrom
const removeFrom: { <T>(array: T[], obj: T): T[]; <T>(array: T[]): (obj: T) => T[] };
Given an array, and an item, if the item is found in the array, it removes it (in-place). The same array is returned
variable resolvePolicies
let resolvePolicies: { when: { LAZY: string; EAGER: string }; async: { WAIT: string; NOWAIT: string };};
variable root
const root: any;
variable services
const services: CoreServices;
variable toJson
const toJson: any;
variable trace
const trace: Trace;
The [[Trace]] singleton
#### Example:
import {trace} from "@uirouter/core";trace.enable(1, 5);
Functions
function all
all: (fn1: Predicate<any>) => (arr: any[]) => boolean;
Check if all the elements of an array match a predicate function
Parameter fn1
a predicate function
fn1
Returns
a function which takes an array and returns true if
fn1
is true for all elements of the array
function allTrueR
allTrueR: (memo: boolean, elem: any) => any;
Reduce function that returns true if all of the values are truthy.
Example 1
let vals = [ 1, true, {}, "hello world"];vals.reduce(allTrueR, true); // truevals.push(0);vals.reduce(allTrueR, true); // false
function ancestors
ancestors: (first: StateObject, second: StateObject) => StateObject[];
Finds the common ancestor path between two states.
Parameter first
The first state.
Parameter second
The second state. {Array} Returns an array of state names in descending order, not including the root.
function and
and: (fn1: Predicate<any>, fn2: Predicate<any>) => Predicate<any>;
Given two functions that return truthy or falsey values, returns a function that returns truthy if both functions return truthy for the given arguments
function any
any: (fn1: Predicate<any>) => (arr: any[]) => boolean;
function anyTrueR
anyTrueR: (memo: boolean, elem: any) => any;
Reduce function that returns true if any of the values are truthy.
*
Example 1
let vals = [ 0, null, undefined ];vals.reduce(anyTrueR, true); // falsevals.push("hello world");vals.reduce(anyTrueR, true); // true
function applyPairs
applyPairs: (memo: TypedMap<any>, keyValTuple: any[]) => TypedMap<any>;
Reduce function which builds an object from an array of [key, value] pairs.
Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.
Each keyValueTuple should be an array with values [ key: string, value: any ]
Example 1
var pairs = [ ["fookey", "fooval"], ["barkey", "barval"] ]var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})// pairsToObj == { fookey: "fooval", barkey: "barval" }// Or, more simply:var pairsToObj = pairs.reduce(applyPairs, {})// pairsToObj == { fookey: "fooval", barkey: "barval" }
function arrayTuples
arrayTuples: (...args: any[]) => any[];
Given two or more parallel arrays, returns an array of tuples where each tuple is composed of [ a[i], b[i], ... z[i] ]
Example 1
let foo = [ 0, 2, 4, 6 ];let bar = [ 1, 3, 5, 7 ];let baz = [ 10, 30, 50, 70 ];arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]
function assertFn
assertFn: (predicateOrMap: Function, errMsg?: string | Function) => any;
function assertMap
assertMap: <T, U>(mapFn: (t: T) => U, errMsg: string | Function) => (t: T) => U;
Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.
Example 1
var data = { foo: 1, bar: 2 };let keys = [ 'foo', 'bar' ]let values = keys.map(assertMap(key => data[key], "Key not found"));// values is [1, 2]let keys = [ 'foo', 'bar', 'baz' ]let values = keys.map(assertMap(key => data[key], "Key not found"));// throws Error("Key not found")
function assertPredicate
assertPredicate: <T>( predicate: Predicate<T>, errMsg: string | Function) => Predicate<T>;
Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.
Example 1
let isNumber = (obj) => typeof(obj) === 'number';let allNumbers = [ 1, 2, 3, 4, 5 ];allNumbers.filter(assertPredicate(isNumber)); //OKlet oneString = [ 1, 2, 3, 4, "5" ];oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers"");
function beforeAfterSubstr
beforeAfterSubstr: (char: string) => (str: string) => string[];
Returns a function that splits a string on a character or substring
function buildUrl
buildUrl: (loc: LocationServices) => string;
function compose
compose: () => () => any;
Given a varargs list of functions, returns a function that composes the argument functions, right-to-left given: f(x), g(x), h(x) let composed = compose(f,g,h) then, composed is: f(g(h(x)))
function copy
copy: (src: Obj, dest?: Obj) => any;
shallow copy from src to dest
function createProxyFunctions
createProxyFunctions: ( source: Function, target: Obj, bind: Function, fnNames?: string[], latebind?: boolean) => Obj;
Builds proxy functions on the
to
object which pass through to thefrom
object.For each key in
fnNames
, creates a proxy function on theto
object. The proxy function calls the real function on thefrom
object.#### Example: This example creates an new class instance whose functions are prebound to the new'd object.
class Foo {constructor(data) {// Binds all functions from Foo.prototype to 'this',// then copies them to 'this'bindFunctions(Foo.prototype, this, this);this.data = data;}log() {console.log(this.data);}}let myFoo = new Foo([1,2,3]);var logit = myFoo.log;logit(); // logs [1, 2, 3] from the myFoo 'this' instance#### Example: This example creates a bound version of a service function, and copies it to another object
var SomeService = {this.data = [3, 4, 5];this.log = function() {console.log(this.data);}}// Constructor fnfunction OtherThing() {// Binds all functions from SomeService to SomeService,// then copies them to 'this'bindFunctions(SomeService, this, SomeService);}let myOtherThing = new OtherThing();myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'Parameter source
A function that returns the source object which contains the original functions to be bound
Parameter target
A function that returns the target object which will receive the bound functions
Parameter bind
A function that returns the object which the functions will be bound to
Parameter fnNames
The function names which will be bound (Defaults to all the functions found on the 'from' object)
Parameter latebind
If true, the binding of the function is delayed until the first time it's invoked
function curry
curry: (fn: Function) => Function;
Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.
Given a function with N parameters, returns a new function that supports partial application. The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters, where M is less than N, it returns a new function that accepts the remaining parameters. It continues to accept more parameters until all N parameters have been supplied.
This contrived example uses a partially applied function as an predicate, which returns true if an object is found in both arrays.
Parameter fn
Returns
{*|function(): (*|any)}
Example 1
// returns true if an object is in both of the two arraysfunction inBoth(array1, array2, object) {return array1.indexOf(object) !== -1 &&array2.indexOf(object) !== 1;}let obj1, obj2, obj3, obj4, obj5, obj6, obj7let foos = [obj1, obj3]let bars = [obj3, obj4, obj5]// A curried "copy" of inBothlet curriedInBoth = curry(inBoth);// Partially apply both the array1 and array2let inFoosAndBars = curriedInBoth(foos, bars);// Supply the final argument; since all arguments are// supplied, the original inBoth function is then called.let obj1InBoth = inFoosAndBars(obj1); // false// Use the inFoosAndBars as a predicate.// Filter, on each iteration, supplies the final argumentlet allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]
function defaults
defaults: (opts: any, ...defaultsList: Obj[]) => any;
Applies a set of defaults to an options object. The options object is filtered to only those properties of the objects in the defaultsList. Earlier objects in the defaultsList take precedence when applying defaults.
function deregAll
deregAll: (functions: Function[]) => void;
Given an array of (deregistration) functions, calls all functions and removes each one from the source array
function eq
eq: (comp: any) => Predicate<any>;
Given a value, returns a Predicate function that returns true if another value is === equal to the original value
function filter
filter: { <T>(collection: T[], callback: (t: T, key?: number) => boolean): T[]; <T>( collection: TypedMap<T>, callback: (t: T, key?: string) => boolean ): TypedMap<T>;};
Given an array of objects, returns a new array containing only the elements which passed the callback predicate
Given an object, returns a new object with only those properties that passed the callback predicate
function find
find: { <T>(collection: TypedMap<T>, callback: Predicate<T>): T; <T>(collection: T[], callback: Predicate<T>): T;};
Given an object, return the first property of that object which passed the callback predicate
Given an array of objects, returns the first object which passed the callback predicate
function flatten
flatten: (arr: any[]) => any;
Return a completely flattened version of an array.
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];flatten(input) // [ "a", "b", "c", "d", "double, "nested" ]
function flattenR
flattenR: (memo: any[], elem: any) => any[];
Reduce function which recursively un-nests all arrays
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];input.reduce(unnestR, []) // [ "a", "b", "c", "d", "double, "nested" ]
function fnToString
fnToString: (fn: IInjectable) => any;
function functionToString
functionToString: (fn: Function) => any;
function getParams
getParams: (queryString: string) => any;
function hashLocationPlugin
hashLocationPlugin: (router: UIRouter) => LocationPlugin;
A
UIRouterPlugin
uses the browser hash to get/set the current location
function identity
identity: (x: any) => any;
function inherit
inherit: (parent: Obj, extra?: Obj) => any;
prototypal inheritance helper. Creates a new object which has
parent
object as its prototype, and then copies the properties fromextra
onto it
function invoke
invoke: { (fnName: string): Function; (fnName: string, args: any[]): Function };
function is
is: <T>(ctor: new (...args: any[]) => T) => (obj: any) => obj is T;
Given a class, returns a Predicate function that returns true if the object is of that class
function isArray
isArray: (arg: any) => arg is any[];
function isDate
isDate: (x: any) => x is Date;
function isFunction
isFunction: (x: any) => x is Function;
function isInjectable
isInjectable: (val: any) => boolean;
Predicate which checks if a value is injectable
A value is "injectable" if it is a function, or if it is an ng1 array-notation-style array where all the elements in the array are Strings, except the last one, which is a Function
function isNull
isNull: (o: any) => boolean;
function isNumber
isNumber: (x: any) => x is number;
function isObject
isObject: (x: any) => boolean;
function isPromise
isPromise: (x: any) => x is Promise<any>;
Predicate which checks if a value looks like a Promise
It is probably a Promise if it's an object, and it has a
then
property which is a Function
function isRegExp
isRegExp: (x: any) => x is RegExp;
function isString
isString: (x: any) => x is string;
function isUndefined
isUndefined: (x: any) => boolean;
function joinNeighborsR
joinNeighborsR: (acc: any[], x: any) => any[];
Reduce fn that joins neighboring strings
Given an array of strings, returns a new array where all neighboring strings have been joined.
#### Example:
let arr = ["foo", "bar", 1, "baz", "", "qux" ];arr.reduce(joinNeighborsR, []) // ["foobar", 1, "bazqux" ]
function kebobString
kebobString: (camelCase: string) => string;
function keyValsToObjectR
keyValsToObjectR: (accum: any, [key, val]: [any, any]) => any;
function locationPluginFactory
locationPluginFactory: ( name: string, isHtml5: boolean, serviceClass: new (uiRouter?: UIRouter) => LocationServices, configurationClass: new ( uiRouter?: UIRouter, isHtml5?: boolean ) => LocationConfig) => (uiRouter: UIRouter) => { name: string; service: LocationServices; configuration: LocationConfig; dispose: (router: UIRouter) => void;};
function makeEvent
makeEvent: ( registry: IHookRegistry, transitionService: TransitionService, eventType: TransitionEventType) => (matchObject: any, callback: any, options?: {}) => any;
Return a registration function of the requested type.
function makeStub
makeStub: <T>(service: string, methods: (keyof T)[]) => T;
function map
map: { <T, U>(collection: T[], callback: Mapper<T, U>, target?: typeof collection): U[]; <T, U>( collection: { [key: string]: T }, callback: Mapper<T, U>, target?: { [key: string]: T } ): { [key: string]: U };};
Given an array, returns a new array, where each element is transformed by the callback function
function mapObj
mapObj: <T, U>( collection: { [key: string]: T }, callback: Mapper<T, U>, target?: { [key: string]: T }) => { [key: string]: U };
Given an object, returns a new object, where each property is transformed by the callback function
function maxLength
maxLength: (max: number, str: string) => string;
Returns a string shortened to a maximum length
If the string is already less than the
max
length, return the string. Else return the string, shortened tomax - 3
and append three dots ("...").Parameter max
the maximum length of the string to return
Parameter str
the input string
function memoryLocationPlugin
memoryLocationPlugin: (router: UIRouter) => LocationPlugin;
A
UIRouterPlugin
that gets/sets the current location from an in-memory object
function mergeR
mergeR: (memo: Obj, item: Obj) => any;
Reduce function that merges each element of the list into a single object, using extend
function noop
noop: () => any;
function not
not: (fn: Predicate<any>) => Predicate<any>;
Given a function that returns a truthy or falsey value, returns a function that returns the opposite (falsey or truthy) value given the same inputs
function omit
omit: (obj: Obj, propNames: string[]) => Obj;
Return a copy of the object omitting the blacklisted properties.
Parameter obj
the source object
Parameter propNames
an Array of strings, which are the blacklisted property names
Example 1
var foo = { a: 1, b: 2, c: 3 };var ab = omit(foo, ['a', 'b']); // { c: 3 }
function or
or: (fn1: Predicate<any>, fn2: Predicate<any>) => Predicate<any>;
Given two functions that return truthy or falsey values, returns a function that returns truthy if at least one of the functions returns truthy for the given arguments
function padString
padString: (length: number, str: string) => string;
Returns a string, with spaces added to the end, up to a desired str length
If the string is already longer than the desired length, return the string. Else returns the string, with extra spaces on the end, such that it reaches
length
characters.Parameter length
the desired length of the string to return
Parameter str
the input string
function pairs
pairs: (obj: Obj) => any[][];
Like _.pairs: Given an object, returns an array of key/value pairs
Example 1
pairs({ foo: "FOO", bar: "BAR }) // [ [ "foo", "FOO" ], [ "bar": "BAR" ] ]
function parse
parse: (name: string) => any;
Given a dotted property name, returns a function that returns a nested property from an object, or undefined let obj = { id: 1, nestedObj: { foo: 1, name: "blarg" }, }; let getName = prop("nestedObj.name"); getName(obj) === "blarg" let propNotFound = prop("this.property.doesnt.exist"); propNotFound(obj) === undefined
function parseUrl
parseUrl: (url: string) => { path: any; search: any; hash: any; url: string };
function pattern
pattern: (struct: Function[][]) => Function;
Sorta like Pattern Matching (a functional programming conditional construct)
See http://c2.com/cgi/wiki?PatternMatching
This is a conditional construct which allows a series of predicates and output functions to be checked and then applied. Each predicate receives the input. If the predicate returns truthy, then its matching output function (mapping function) is provided with the input and, then the result is returned.
Each combination (2-tuple) of predicate + output function should be placed in an array of size 2: [ predicate, mapFn ]
These 2-tuples should be put in an outer array.
Parameter struct
A 2D array. Each element of the array should be an array, a 2-tuple, with a Predicate and a mapping/output function
Returns
{function(any): *}
Example 1
// Here's a 2-tuple where the first element is the isString predicate// and the second element is a function that returns a description of the inputlet firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];// Second tuple: predicate "isNumber", mapfn returns a descriptionlet secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];let third = [ (input) => input === null, (input) => `Oh, null...` ];let fourth = [ (input) => input === undefined, (input) => `notdefined` ];let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);console.log(descriptionOf(undefined)); // 'notdefined'console.log(descriptionOf(55)); // '(55) That's a number!'console.log(descriptionOf("foo")); // 'Here's your string foo'
function pick
pick: (obj: Obj, propNames: string[]) => Obj;
Return a copy of the object only containing the whitelisted properties.
#### Example:
var foo = { a: 1, b: 2, c: 3 };var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }Parameter obj
the source object
Parameter propNames
an Array of strings, which are the whitelisted property names
function pipe
pipe: (...funcs: Function[]) => (obj: any) => any;
Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right given: f(x), g(x), h(x) let piped = pipe(f,g,h); then, piped is: h(g(f(x)))
function pluck
pluck: { <T>(collection: Obj[], propName: string): T[]; (collection: { [key: string]: any }, propName: string): { [key: string]: any };};
Given an array of objects, maps each element to a named property of the element.
Given an object, maps each property of the object to a named property of the property.
function prop
prop: (name: string) => (obj: any) => any;
Given a property name, returns a function that returns that property from an object let obj = { foo: 1, name: "blarg" }; let getName = prop("name"); getName(obj) === "blarg"
function pushR
pushR: (arr: any[], obj: any) => any[];
Reduce function that pushes an object to an array, then returns the array. Mostly just for [[flattenR]] and [[uniqR]]
function pushStateLocationPlugin
pushStateLocationPlugin: (router: UIRouter) => LocationPlugin;
A
UIRouterPlugin
that gets/sets the current location using the browser'slocation
andhistory
apis
function resolvablesBuilder
resolvablesBuilder: (state: StateObject) => Resolvable[];
This is a [[StateBuilder.builder]] function for the
resolve:
block on a [[StateDeclaration]].When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder validates the
resolve
property and converts it to a [[Resolvable]] array.resolve: input value can be:
{ // analyzed but not injected myFooResolve: function() { return "myFooData"; },
// function.toString() parsed, "DependencyName" dep as string (not min-safe) myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },
// Array split; "DependencyName" dep as string myBazResolve: [ "DependencyName", function(dep) { return dep.fetchSomethingAsPromise() },
// Array split; DependencyType dep as token (compared using ===) myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },
// val.$inject used as deps // where: // corgeResolve.$inject = ["DependencyName"]; // function corgeResolve(dep) { dep.fetchSometingAsPromise() } // then "DependencyName" dep as string myCorgeResolve: corgeResolve,
// inject service by name // When a string is found, desugar creating a resolve that injects the named service myGraultResolve: "SomeService" }
or:
[ new Resolvable("myFooResolve", function() { return "myFooData" }), new Resolvable("myBarResolve", function(dep) { return dep.fetchSomethingAsPromise() }, [ "DependencyName" ]), { provide: "myBazResolve", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ "DependencyName" ] } ]
function servicesPlugin
servicesPlugin: (router: UIRouter) => ServicesPlugin;
function silenceUncaughtInPromise
silenceUncaughtInPromise: (promise: Promise<any>) => Promise<any>;
function silentRejection
silentRejection: (error: any) => Promise<any>;
function splitEqual
splitEqual: (str: string) => string[];
function splitHash
splitHash: (str: string) => string[];
function splitOnDelim
splitOnDelim: (delim: string) => (str: string) => string[];
Splits on a delimiter, but returns the delimiters in the array
#### Example:
var splitOnSlashes = splitOnDelim('/');splitOnSlashes("/foo"); // ["/", "foo"]splitOnSlashes("/foo/"); // ["/", "foo", "/"]
function splitQuery
splitQuery: (str: string) => string[];
function stringify
stringify: (o: any) => string;
function stripLastPathElement
stripLastPathElement: (str: string) => string;
function tail
tail: <T>(arr: T[]) => T;
Get the last element of an array
function trimHashVal
trimHashVal: (str: string) => string;
function uniqR
uniqR: <T>(acc: T[], token: T) => T[];
Reduce function that filters out duplicates
function unnest
unnest: (arr: any[]) => any;
Return a new array with a single level of arrays unnested.
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];unnest(input) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
function unnestR
unnestR: (memo: any[], elem: any[]) => any[];
Reduce function which un-nests a single level of arrays
Example 1
let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ];input.reduce(unnestR, []) // [ "a", "b", "c", "d", [ "double, "nested" ] ]
function val
val: <T>(v: T) => () => T;
Given a value, returns a function which returns the value
function values
values: <T>(obj: TypedMap<T>) => T[];
Given an object, return its enumerable property values
Example 1
let foo = { a: 1, b: 2, c: 3 }let vals = values(foo); // [ 1, 2, 3 ]
Classes
class BaseLocationServices
abstract class BaseLocationServices implements LocationServices, Disposable {}
A base
LocationServices
constructor
constructor(router: UIRouter, fireAfterUpdate: boolean);
property fireAfterUpdate
fireAfterUpdate: boolean;
property hash
hash: () => any;
property path
path: () => any;
property search
search: () => any;
method dispose
dispose: (router: UIRouter) => void;
method onChange
onChange: (cb: EventListener) => () => Function[];
method url
url: (url?: string, replace?: boolean) => string;
class BrowserLocationConfig
class BrowserLocationConfig implements LocationConfig {}
A
LocationConfig
that delegates to the browser'slocation
object
constructor
constructor(router?: any, _isHtml5?: boolean);
method baseHref
baseHref: (href?: string) => string;
method dispose
dispose: () => void;
method hashPrefix
hashPrefix: () => string;
method host
host: () => string;
method html5Mode
html5Mode: () => boolean;
method port
port: () => number;
method protocol
protocol: () => string;
class Glob
class Glob {}
constructor
constructor(text: string);
property glob
glob: string[];
property regexp
regexp: RegExp;
property text
text: string;
method fromString
static fromString: (text: string) => Glob;
Returns a glob from the string, or null if the string isn't Glob-like
method is
static is: (text: string) => boolean;
Returns true if the string has glob-like characters in it
method matches
matches: (name: string) => boolean;
class HashLocationService
class HashLocationService extends BaseLocationServices {}
A
LocationServices
that uses the browser hash "#" to get/set the current location
constructor
constructor(router: UIRouter);
method dispose
dispose: (router: UIRouter) => void;
class HookBuilder
class HookBuilder {}
This class returns applicable TransitionHooks for a specific Transition instance.
Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g. myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is determined by the type of hook)
The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition.
The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private in the Transition class, so we must also provide the Transition's _treeChanges)
constructor
constructor(transition: Transition);
method buildHooks
buildHooks: (hookType: TransitionEventType) => TransitionHook[];
Returns an array of newly built TransitionHook objects.
- Finds all RegisteredHooks registered for the given
hookType
which matched the transition's [[TreeChanges]]. - Finds [[PathNode]] (orPathNode[]
) to use as the TransitionHook context(s) - For each of the [[PathNode]]s, creates a TransitionHookParameter hookType
the type of the hook registration function, e.g., 'onEnter', 'onFinish'.
method buildHooksForPhase
buildHooksForPhase: (phase: TransitionHookPhase) => TransitionHook[];
method getMatchingHooks
getMatchingHooks: ( hookType: TransitionEventType, treeChanges: TreeChanges, transition: Transition) => RegisteredHook[];
Finds all RegisteredHooks from: - The Transition object instance hook registry - The TransitionService ($transitions) global hook registry
which matched: - the eventType - the matchCriteria (to, from, exiting, retained, entering)
Returns
an array of matched [[RegisteredHook]]s
class MemoryLocationConfig
class MemoryLocationConfig implements LocationConfig {}
A
LocationConfig
mock that gets/sets all config from an in-memory object
class MemoryLocationService
class MemoryLocationService extends BaseLocationServices {}
A
LocationServices
that gets/sets the current location from an in-memory object
constructor
constructor(router: UIRouter);
class Param
class Param {}
constructor
constructor( id: string, type: ParamType, location: DefType, urlConfig: UrlConfig, state: StateDeclaration);
property array
array: boolean;
property config
config: any;
property dynamic
dynamic: boolean;
property id
id: string;
property inherit
inherit: boolean;
property isOptional
isOptional: boolean;
property location
location: DefType;
property raw
raw: boolean;
property replace
replace: [{ to: any; from: any }];
property squash
squash: string | boolean;
property type
type: ParamType;
method changed
static changed: ( params: Param[], values1?: RawParams, values2?: RawParams) => Param[];
Finds [[Param]] objects which have different param values
Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects
Parameter params
: The list of Param objects to filter
Parameter values1
: The first set of parameter values
Parameter values2
: the second set of parameter values
Returns
any Param objects whose values were different between values1 and values2
method equals
static equals: (params: Param[], values1?: {}, values2?: {}) => boolean;
Checks if two param value objects are equal (for a set of [[Param]] objects)
Parameter params
The list of [[Param]] objects to check
Parameter values1
The first set of param values
Parameter values2
The second set of param values
Returns
true if the param values in values1 and values2 are equal
method isDefaultValue
isDefaultValue: (value: any) => boolean;
method isSearch
isSearch: () => boolean;
method toString
toString: () => string;
method validates
static validates: (params: Param[], values?: RawParams) => boolean;
Returns true if a the parameter values are valid, according to the Param definitions
method value
value: (value?: any) => any;
[Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the default value, which may be the result of an injectable function.
method values
static values: (params: Param[], values?: RawParams) => RawParams;
class ParamFactory
class ParamFactory {}
constructor
constructor(router: UIRouter);
method fromConfig
fromConfig: (id: string, type: ParamType, state: StateDeclaration) => Param;
method fromPath
fromPath: (id: string, type: ParamType, state: StateDeclaration) => Param;
method fromSearch
fromSearch: (id: string, type: ParamType, state: StateDeclaration) => Param;
class ParamType
class ParamType implements ParamTypeDefinition {}
An internal class which implements [[ParamTypeDefinition]].
A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types. When a param type definition is registered, an instance of this class is created internally.
This class has naive implementations for all the [[ParamTypeDefinition]] methods.
Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values.
#### Example:
var paramTypeDef = {decode: function(val) { return parseInt(val, 10); },encode: function(val) { return val && val.toString(); },equals: function(a, b) { return this.is(a) && a === b; },is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; },pattern: /\d+/}var paramType = new ParamType(paramTypeDef);
constructor
constructor(def: ParamTypeDefinition);
Parameter def
A configuration object which contains the custom type definition. The object's properties will override the default methods and/or pattern in
ParamType
's public interface.Returns
a new ParamType object
property dynamic
dynamic: boolean;
property inherit
inherit: boolean;
property name
name: string;
The name/id of the parameter type
property pattern
pattern: RegExp;
property raw
raw: boolean;
method $asArray
$asArray: (mode: boolean | 'auto', isSearch: boolean) => any;
Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'. e.g.: - urlmatcher pattern "/path?{queryParam[]:int}" - url: "/path?queryParam=1&queryParam=2 - $stateParams.queryParam will be [1, 2] if
mode
is "auto", then - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
method $normalize
$normalize: (val: any) => any;
Given an encoded string, or a decoded object, returns a decoded object
method $subPattern
$subPattern: () => string;
method decode
decode: (val: string, key?: string) => any;
method encode
encode: (val: any, key?: string) => string | string[];
method equals
equals: (a: any, b: any) => boolean;
method is
is: (val: any, key?: string) => boolean;
method toString
toString: () => string;
class ParamTypes
class ParamTypes {}
A registry for parameter types.
This registry manages the built-in (and custom) parameter types.
The built-in parameter types are:
- [[string]] - [[path]] - [[query]] - [[hash]] - [[int]] - [[bool]] - [[date]] - [[json]] - [[any]]
To register custom parameter types, use [[UrlConfig.type]], i.e.,
router.urlService.config.type(customType)
constructor
constructor();
property any
static any: ParamTypeDefinition;
Built-in parameter type:
any
This parameter type is used by default for url-less parameters (parameters that do not appear in the URL). This type does not encode or decode. It is compared using a deep
equals
comparison.#### Example: This example defines a non-url parameter on a [[StateDeclaration]].
.state({name: 'new',url: '/new',params: {inrepyto: null}});$state.go('new', { inreplyto: currentMessage });
property bool
static bool: ParamTypeDefinition;
Built-in parameter type:
bool
This parameter type serializes
true
/false
as1
/0
#### Example:
.state({name: 'inbox',url: '/inbox?{unread:bool}'});$state.go('inbox', { unread: true });The URL will serialize to:
/inbox?unread=1
.Conversely, if the url is
/inbox?unread=0
, the value of theunread
parameter will be afalse
.
property date
static date: ParamTypeDefinition;
Built-in parameter type:
date
This parameter type can be used to serialize Javascript dates as parameter values.
#### Example:
.state({name: 'search',url: '/search?{start:date}'});$state.go('search', { start: new Date(2000, 0, 1) });The URL will serialize to:
/search?start=2000-01-01
.Conversely, if the url is
/search?start=2016-12-25
, the value of thestart
parameter will be aDate
object where:-
date.getFullYear() === 2016
-date.getMonth() === 11
(month is 0-based) -date.getDate() === 25
property enqueue
enqueue: boolean;
property hash
static hash: ParamTypeDefinition;
Built-in parameter type:
hash
This parameter type is used for the
#
parameter (the hash) It behaves the same as the [[string]] parameter type.
property int
static int: ParamTypeDefinition;
Built-in parameter type:
int
This parameter type serializes javascript integers (
number
s which represent an integer) to the URL.#### Example:
.state({name: 'user',url: '/user/{id:int}'});$state.go('user', { id: 1298547 });The URL will serialize to:
/user/1298547
.When the parameter value is read, it will be the
number
1298547
, not the string"1298547"
.
property json
static json: ParamTypeDefinition;
Built-in parameter type:
json
This parameter type can be used to serialize javascript objects into the URL using JSON serialization.
#### Example: This example serializes an plain javascript object to the URL
.state({name: 'map',url: '/map/{coords:json}'});$state.go('map', { coords: { x: 10399.2, y: 49071 });The URL will serialize to:
/map/%7B%22x%22%3A10399.2%2C%22y%22%3A49071%7D
property path
static path: ParamTypeDefinition;
Built-in parameter type:
path
This parameter type is the default type for path parameters. A path parameter is any parameter declared in the path portion of a url
-
/foo/:param1/:param2
: two path parametersThis parameter type behaves exactly like the [[string]] type with one exception. When matching parameter values in the URL, the
path
type does not match forward slashes/
.#### Angular 1 note: In ng1, this type is overridden with one that pre-encodes slashes as
~2F
instead of%2F
. For more details about this angular 1 behavior, see: https://github.com/angular-ui/ui-router/issues/2598
property query
static query: ParamTypeDefinition;
Built-in parameter type:
query
This parameter type is the default type for query/search parameters. It behaves the same as the [[string]] parameter type.
A query parameter is any parameter declared in the query/search portion of a url
-
/bar?param2
: a query parameter
property string
static string: ParamTypeDefinition;
Built-in parameter type:
string
This parameter type coerces values to strings. It matches anything (
new RegExp(".*")
) in the URL
property typeQueue
typeQueue: any[];
property types
types: any;
method dispose
dispose: () => void;
method type
type: ( name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) => any;
Registers a parameter type
End users should call [[UrlMatcherFactory.type]], which delegates to this method.
class PathNode
class PathNode {}
A node in a [[TreeChanges]] path
For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path. Each PathNode corresponds to a state being entered, exited, or retained. The stateful information includes parameter values and resolve data.
constructor
constructor(node: PathNode);
Creates a copy of a PathNode
constructor
constructor(state: StateObject);
Creates a new (empty) PathNode for a State
property clone
static clone: (node: PathNode) => PathNode;
Returns a clone of the PathNode
Deprecated
use instance method
node.clone()
property paramSchema
paramSchema: Param[];
The parameters declared on the state
property paramValues
paramValues: { [key: string]: any };
The parameter values that belong to the state
property resolvables
resolvables: Resolvable[];
The individual (stateful) resolvable objects that belong to the state
property state
state: StateObject;
The state being entered, exited, or retained
property views
views: ViewConfig[];
The state's declared view configuration objects
method applyRawParams
applyRawParams: (params: RawParams) => PathNode;
Sets [[paramValues]] for the node, from the values of an object hash
method clone
clone: () => PathNode;
method diff
diff: (node: PathNode, paramsFn?: GetParamsFn) => Param[] | false;
Finds Params with different parameter values on another PathNode.
Given another node (of the same state), finds the parameter values which differ. Returns the [[Param]] (schema objects) whose parameter values differ.
Given another node for a different state, returns
false
Parameter node
The node to compare to
Parameter paramsFn
A function that returns which parameters should be compared.
Returns
The [[Param]]s which differ, or null if the two nodes are for different states
method equals
equals: (node: PathNode, paramsFn?: GetParamsFn) => boolean;
Returns
true if the state and parameter values for another PathNode are equal to the state and param values for this PathNode
method parameter
parameter: (name: string) => Param;
Gets a specific [[Param]] metadata that belongs to the node
class PathUtils
class PathUtils {}
This class contains functions which convert TargetStates, Nodes and paths from one type to another.
property nonDynamicParams
static nonDynamicParams: (node: PathNode) => Param[];
property paramValues
static paramValues: (path: PathNode[]) => any;
Gets the raw parameter values from a path
method applyViewConfigs
static applyViewConfigs: ( $view: ViewService, path: PathNode[], states: StateObject[]) => void;
Creates ViewConfig objects and adds to nodes.
On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state
method buildPath
static buildPath: (targetState: TargetState) => PathNode[];
method buildToPath
static buildToPath: ( fromPath: PathNode[], targetState: TargetState) => PathNode[];
Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[]
method equals
static equals: ( pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn) => boolean;
Returns true if two paths are identical.
Parameter pathA
Parameter pathB
Parameter paramsFn
a function which returns the parameters to consider when comparing
Returns
true if the the states and parameter values for both paths are identical
method inheritParams
static inheritParams: ( fromPath: PathNode[], toPath: PathNode[], toKeys?: string[]) => PathNode[];
Given a fromPath and a toPath, returns a new to path which inherits parameters from the fromPath
For a parameter in a node to be inherited from the from path: - The toPath's node must have a matching node in the fromPath (by state). - The parameter name must not be found in the toKeys parameter array.
Note: the keys provided in toKeys are intended to be those param keys explicitly specified by some caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams, it is not inherited from the fromPath.
method makeTargetState
static makeTargetState: ( registry: StateRegistry, path: PathNode[]) => TargetState;
Given a PathNode[], create an TargetState
method matching
static matching: ( pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn) => PathNode[];
Returns a new path which is: the subpath of the first path which matches the second path.
The new path starts from root and contains any nodes that match the nodes in the second path. It stops before the first non-matching node.
Nodes are compared using their state property and their parameter values. If a
paramsFn
is provided, only the [[Param]] returned by the function will be considered when comparing nodes.Parameter pathA
the first path
Parameter pathB
the second path
Parameter paramsFn
a function which returns the parameters to consider when comparing
Returns
an array of PathNodes from the first path which match the nodes in the second path
method subPath
static subPath: (path: PathNode[], predicate: Predicate<PathNode>) => PathNode[];
Return a subpath of a path, which stops at the first matching node
Given an array of nodes, returns a subset of the array starting from the first node, stopping when the first node matches the predicate.
Parameter path
a path of [[PathNode]]s
Parameter predicate
a [[Predicate]] fn that matches [[PathNode]]s
Returns
a subpath up to the matching node, or undefined if no match is found
method treeChanges
static treeChanges: ( fromPath: PathNode[], toPath: PathNode[], reloadState: StateObject) => TreeChanges;
Computes the tree changes (entering, exiting) between a fromPath and toPath.
class PushStateLocationService
class PushStateLocationService extends BaseLocationServices {}
A
LocationServices
that gets/sets the current location using the browser'slocation
andhistory
apisUses
history.pushState
andhistory.replaceState
constructor
constructor(router: UIRouter);
method dispose
dispose: (router: UIRouter) => void;
class Queue
class Queue<T> {}
constructor
constructor(_items?: T[], _limit?: number);
property onEvict
onEvict: (val: (item: T) => void) => (item: T) => void;
method clear
clear: () => Array<T>;
method dequeue
dequeue: () => T;
method enqueue
enqueue: (item: T) => T;
method evict
evict: () => T;
method peekHead
peekHead: () => T;
method peekTail
peekTail: () => T;
method remove
remove: (item: T) => T;
method size
size: () => number;
class RegisteredHook
class RegisteredHook {}
The registration data for a registered transition hook
constructor
constructor( tranSvc: TransitionService, eventType: TransitionEventType, callback: HookFn, matchCriteria: HookMatchCriteria, removeHookFromRegistry: (hook: RegisteredHook) => void, options?: HookRegOptions);
property bind
bind: any;
property callback
callback: HookFn;
property eventType
eventType: TransitionEventType;
property invokeCount
invokeCount: number;
property invokeLimit
invokeLimit: number;
property matchCriteria
matchCriteria: HookMatchCriteria;
property priority
priority: number;
property removeHookFromRegistry
removeHookFromRegistry: (hook: RegisteredHook) => void;
property tranSvc
tranSvc: TransitionService;
method deregister
deregister: () => void;
method matches
matches: (treeChanges: TreeChanges, transition: Transition) => IMatchingNodes;
Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]]
Returns
an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering)
class Rejection
class Rejection {}
constructor
constructor(type: number, message?: string, detail?: any);
property detail
detail: any;
A detail object
This value varies based on the mechanism for rejecting the transition. For example, if an error was thrown from a hook, the
detail
will be theError
object. If a hook returned a rejected promise, thedetail
will be the rejected value.
property message
message: string;
A message describing the rejection
property redirected
redirected: boolean;
Indicates if the transition was redirected.
When a transition is redirected, the rejection [[type]] will be [[RejectType.SUPERSEDED]] and this flag will be true.
property type
type: RejectType;
The type of the rejection.
This value is an number representing the type of transition rejection. If using Typescript, this is a Typescript enum.
- [[RejectType.SUPERSEDED]] (
2
) - [[RejectType.ABORTED]] (3
) - [[RejectType.INVALID]] (4
) - [[RejectType.IGNORED]] (5
) - [[RejectType.ERROR]] (6
)
method aborted
static aborted: (detail?: any) => Rejection;
Returns a Rejection due to aborted transition
method errored
static errored: (detail?: any) => Rejection;
Returns a Rejection due to aborted transition
method ignored
static ignored: (detail?: any) => Rejection;
Returns a Rejection due to ignored transition
method invalid
static invalid: (detail?: any) => Rejection;
Returns a Rejection due to invalid transition
method isRejectionPromise
static isRejectionPromise: (obj: any) => boolean;
Returns true if the obj is a rejected promise created from the
asPromise
factory
method normalize
static normalize: (detail?: Rejection | Error | any) => Rejection;
Returns a Rejection
Normalizes a value as a Rejection. If the value is already a Rejection, returns it. Otherwise, wraps and returns the value as a Rejection (Rejection type: ERROR).
Returns
detail
if it is already aRejection
, else returns an ERROR Rejection.
method redirected
static redirected: (detail?: any) => Rejection;
Returns a Rejection due to redirected transition
method superseded
static superseded: (detail?: any, options?: any) => Rejection;
Returns a Rejection due to transition superseded
method toPromise
toPromise: () => Promise<any>;
method toString
toString: () => string;
class Resolvable
class Resolvable implements ResolvableLiteral {}
The basic building block for the resolve system.
Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise), and the unwrapped-when-complete (.data) result of the resolveFn.
Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the resolveFn) and returns the resulting promise.
Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first parameter to those fns.
constructor
constructor(resolvable: Resolvable);
This constructor creates a Resolvable copy
constructor
constructor(resolvable: ResolvableLiteral);
This constructor creates a new Resolvable from the plain old [[ResolvableLiteral]] javascript object
constructor
constructor( token: any, resolveFn: Function, deps?: any[], policy?: ResolvePolicy, data?: any);
This constructor creates a new
Resolvable
#### Example:
var resolvable1 = new Resolvable('mytoken', http => http.get('foo.json').toPromise(), [Http]);var resolvable2 = new Resolvable(UserService, dep => new UserService(dep.data), [SomeDependency]);var resolvable1Clone = new Resolvable(resolvable1);Parameter token
The new resolvable's injection token, such as
"userList"
(a string) orUserService
(a class). When this token is used during injection, the resolved value will be injected.Parameter resolveFn
The function that returns the resolved value, or a promise for the resolved value
Parameter deps
An array of dependencies, which will be injected into the
resolveFn
Parameter policy
the [[ResolvePolicy]] defines when and how the Resolvable is processed
Parameter data
Pre-resolved data. If the resolve value is already known, it may be provided here.
property data
data: any;
property deps
deps: any[];
property fromData
static fromData: (token: any, data: any) => Resolvable;
property policy
policy: ResolvePolicy;
property promise
promise: Promise<any>;
property resolved
resolved: boolean;
property resolveFn
resolveFn: Function;
property token
token: any;
method clone
clone: () => Resolvable;
method get
get: (resolveContext: ResolveContext, trans?: Transition) => Promise<any>;
Gets a promise for this Resolvable's data.
Fetches the data and returns a promise. Returns the existing promise if it has already been fetched once.
method getPolicy
getPolicy: (state: StateObject) => ResolvePolicy;
method resolve
resolve: (resolveContext: ResolveContext, trans?: Transition) => Promise<any>;
Asynchronously resolve this Resolvable's data
Given a ResolveContext that this Resolvable is found in: Wait for this Resolvable's dependencies, then invoke this Resolvable's function and update the Resolvable's state
method toString
toString: () => string;
class ResolveContext
class ResolveContext {}
Encapsulates Dependency Injection for a path of nodes
UI-Router states are organized as a tree. A nested state has a path of ancestors to the root of the tree. When a state is being activated, each element in the path is wrapped as a [[PathNode]]. A
PathNode
is a stateful object that holds things like parameters and resolvables for the state being activated.The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path.
constructor
constructor(_path: PathNode[]);
method addResolvables
addResolvables: (newResolvables: Resolvable[], state: StateObject) => void;
Adds Resolvables to the node that matches the state
This adds a [[Resolvable]] (generally one created on the fly; not declared on a [[StateDeclaration.resolve]] block). The resolvable is added to the node matching the
state
parameter.These new resolvables are not automatically fetched. The calling code should either fetch them, fetch something that depends on them, or rely on [[resolvePath]] being called when some state is being entered.
Note: each resolvable's [[ResolvePolicy]] is merged with the state's policy, and the global default.
Parameter newResolvables
the new Resolvables
Parameter state
Used to find the node to put the resolvable on
method findNode
findNode: (resolvable: Resolvable) => PathNode;
method getDependencies
getDependencies: (resolvable: Resolvable) => Resolvable[];
Gets the async dependencies of a Resolvable
Given a Resolvable, returns its dependencies as a Resolvable[]
method getPolicy
getPolicy: (resolvable: Resolvable) => ResolvePolicy;
Returns the [[ResolvePolicy]] for the given [[Resolvable]]
method getResolvable
getResolvable: (token: any) => Resolvable;
Gets the Resolvable that matches the token
Gets the last Resolvable that matches the token in this context, or undefined. Throws an error if it doesn't exist in the ResolveContext
method getTokens
getTokens: () => any[];
Gets all the tokens found in the resolve context, de-duplicated
method injector
injector: () => UIInjector;
method resolvePath
resolvePath: ( when?: PolicyWhen, trans?: Transition) => Promise<{ token: any; value: any }[]>;
Returns a promise for an array of resolved path Element promises
Parameter when
Parameter trans
Returns
{Promise|any}
method subContext
subContext: (state: StateObject) => ResolveContext;
Returns a ResolveContext that includes a portion of this one
Given a state, this method creates a new ResolveContext from this one. The new context starts at the first node (root) and stops at the node for the
state
parameter.#### Why
When a transition is created, the nodes in the "To Path" are injected from a ResolveContext. A ResolveContext closes over a path of [[PathNode]]s and processes the resolvables. The "To State" can inject values from its own resolvables, as well as those from all its ancestor state's (node's). This method is used to create a narrower context when injecting ancestor nodes.
Example 1
let ABCD = new ResolveContext([A, B, C, D]);
Given a path
[A, B, C, D]
, whereA
,B
,C
andD
are nodes for statesa
,b
,c
,d
: When injectingD
,D
should have access to all resolvables fromA
,B
,C
,D
. However,B
should only be able to access resolvables fromA
,B
.When resolving for the
B
node, first take the full "To Path" Context[A,B,C,D]
and limit to the subpath[A,B]
.let AB = ABCD.subcontext(a)
class StateBuilder
class StateBuilder {}
A internal global service
StateBuilder is a factory for the internal [[StateObject]] objects.
When you register a state with the [[StateRegistry]], you register a plain old javascript object which conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding [[StateObject]] object, which has an API and is used internally.
Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function using the [[builder]] method.
constructor
constructor(matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory);
method build
build: (state: StateObject) => StateObject;
Builds all of the properties on an essentially blank State object, returning a State object which has all its properties and API built.
Parameter state
an uninitialized State object
Returns
the built State object
method builder
builder: { (property: string, fn: BuilderFunction): Function; (property: string): BuilderFunction | BuilderFunction[];};
Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g.,
parent
,url
, orpath
). More than one BuilderFunction can be registered for a given property.The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.
Parameter property
The name of the State property being registered for.
Parameter fn
The BuilderFunction which will be used to build the State property
Returns
a function which deregisters the BuilderFunction
Gets the registered builder functions for a given property of [[StateObject]].
Parameter property
The name of the State property being registered for.
Returns
the registered builder(s). note: for backwards compatibility, this may be a single builder or an array of builders
method name
name: (state: StateObject) => string;
method parentName
parentName: (state: StateObject) => string;
class StateMatcher
class StateMatcher {}
constructor
constructor(_states: { [key: string]: StateObject });
method find
find: ( stateOrName: StateOrName, base?: StateOrName, matchGlob?: boolean) => StateObject;
method isRelative
isRelative: (stateName: string) => boolean;
method resolvePath
resolvePath: (name: string, base: StateOrName) => string;
class StateObject
class StateObject {}
Internal representation of a UI-Router state.
Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].
A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.
This class prototypally inherits from the corresponding [[StateDeclaration]]. Each of its own properties (i.e.,
hasOwnProperty
) are built using builders from the [[StateBuilder]].
constructor
constructor(config?: StateDeclaration);
Deprecated
use State.create()
property abstract
abstract: boolean;
Prototypally inherits from [[StateDeclaration.abstract]]
property data
data: any;
Prototypally inherits from [[StateDeclaration.data]] Note: This is the only field on the [[StateDeclaration]] which is mutated. The definition object's
data
field is replaced with a new object which prototypally inherits from the parent state definition'sdata
field.
property includes
includes: { [name: string]: boolean };
An object containing the parent States' names as keys and true as their values.
property isState
static isState: (obj: any) => obj is StateObject;
Predicate which returns true if the object is an internal [[StateObject]] object
property isStateClass
static isStateClass: ( stateDecl: _StateDeclaration) => stateDecl is new () => StateDeclaration;
Predicate which returns true if the object is an class with @State() decorator
property isStateDeclaration
static isStateDeclaration: (obj: any) => obj is StateDeclaration;
Predicate which returns true if the object is a [[StateDeclaration]] object
property lazyLoad
lazyLoad: ( transition: Transition, state: StateDeclaration) => Promise<LazyLoadResult>;
Prototypally inherits from [[StateDeclaration.lazyLoad]]
property name
name: string;
The name used to register the state
property navigable
navigable: StateObject;
The nearest parent [[StateObject]] which has a URL
property onEnter
onEnter: TransitionStateHookFn;
Prototypally inherits from [[StateDeclaration.onEnter]]
property onExit
onExit: TransitionStateHookFn;
Prototypally inherits from [[StateDeclaration.onExit]]
property onRetain
onRetain: TransitionStateHookFn;
Prototypally inherits from [[StateDeclaration.onRetain]]
property params
params: { [key: string]: Param };
The parameters for the state, built from the URL and [[StateDeclaration.params]]
property parent
parent: StateObject;
The parent [[StateObject]]
property path
path: StateObject[];
The parent [[StateObject]] objects from this state up to the root
property redirectTo
redirectTo: | string | (($transition$: Transition) => TargetState) | { state: string | StateDeclaration; params: { [key: string]: any } };
Prototypally inherits from [[StateDeclaration.redirectTo]]
property resolvables
resolvables: Resolvable[];
A list of [[Resolvable]] objects. The internal representation of [[resolve]].
property resolve
resolve: any[] | { [key: string]: string | Function | any[] };
Prototypally inherits from [[StateDeclaration.resolve]]
property resolvePolicy
resolvePolicy: any;
Prototypally inherits from [[StateDeclaration.resolvePolicy]]
property self
self: StateDeclaration;
The original [[StateDeclaration]] used to build this [[StateObject]]. Note:
this
object also prototypally inherits from theself
declaration object.
property url
url: UrlMatcher;
A compiled URLMatcher which detects when the state's URL is matched
property views
views: { [key: string]: _ViewDeclaration };
The views for the state. Note:
@uirouter/core
does not register a builder for views. The framework specific code should register aviews
builder.
method create
static create: (stateDecl: _StateDeclaration) => StateObject;
Create a state object to put the private/internal implementation details onto. The object's prototype chain looks like: (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)
Parameter stateDecl
the user-supplied State Declaration
Returns
{StateObject} an internal State object
method fqn
fqn: () => string;
Returns
Returns a dot-separated name of the state.
Deprecated
this does not properly handle dot notation
method is
is: (ref: StateObject | StateDeclaration | string) => boolean;
Returns true if the provided parameter is the same state.
Compares the identity of the state against the passed value, which is either an object reference to the actual
State
instance, the original definition object passed to$stateProvider.state()
, or the fully-qualified name.Parameter ref
Can be one of (a) a
State
instance, (b) an object that was passed into$stateProvider.state()
, (c) the fully-qualified name of a state as a string.Returns
Returns
true
ifref
matches the currentState
instance.
method parameter
parameter: (id: string, opts?: { inherit?: boolean }) => Param;
Returns a single [[Param]] that is owned by the state
If
opts.inherit
is true, it also searches the ancestor states` [[Param]]s.Parameter id
the name of the [[Param]] to return
Parameter opts
options
method parameters
parameters: (opts?: { inherit?: boolean; matchingKeys?: any }) => Param[];
Gets the state's
Param
objectsGets the list of [[Param]] objects owned by the state. If
opts.inherit
is true, it also includes the ancestor states' [[Param]] objects. Ifopts.matchingKeys
exists, returns onlyParam
s whoseid
is a key on thematchingKeys
objectParameter opts
options
method root
root: () => StateObject;
Returns the root node of this state's tree.
Returns
The root of this state's tree.
method toString
toString: () => string;
class StateParams
class StateParams {}
constructor
constructor(params?: Obj);
method $inherit
$inherit: (newParams: Obj, $current: StateObject, $to: StateObject) => any;
Merges a set of parameters with all parameters inherited between the common parents of the current state and a given destination state.
Parameter newParams
The set of parameters which will be composited with inherited params.
Parameter $current
Internal definition of object representing the current state.
Parameter $to
Internal definition of object representing state to transition to.
class StateQueueManager
class StateQueueManager implements Disposable {}
constructor
constructor( router: UIRouter, states: { [key: string]: StateObject }, builder: StateBuilder, listeners: StateRegistryListener[]);
property builder
builder: StateBuilder;
property listeners
listeners: StateRegistryListener[];
property queue
queue: StateObject[];
property states
states: { [key: string]: StateObject };
method attachRoute
attachRoute: (state: StateObject) => void;
method dispose
dispose: () => void;
method flush
flush: () => { [key: string]: StateObject };
method register
register: (stateDecl: _StateDeclaration) => StateObject;
class StateRegistry
class StateRegistry {}
A registry for all of the application's [[StateDeclaration]]s
This API is found at
router.stateRegistry
([[UIRouter.stateRegistry]])
method decorator
decorator: (property: string, builderFunction: BuilderFunction) => Function;
Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g.,
parent
,url
, orpath
). More than one BuilderFunction can be registered for a given property.The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.
Parameter property
The name of the State property being registered for.
Parameter builderFunction
The BuilderFunction which will be used to build the State property
Returns
a function which deregisters the BuilderFunction
method deregister
deregister: (stateOrName: StateOrName) => StateObject[];
Removes a state from the registry
This removes a state from the registry. If the state has children, they are are also removed from the registry.
Parameter stateOrName
the state's name or object representation
Returns
{StateObject[]} a list of removed states
method get
get: { (): StateDeclaration[]; (stateOrName: StateOrName, base?: StateOrName): StateDeclaration;};
Gets all registered states
Calling this method with no arguments will return a list of all the states that are currently registered. Note: this does not return states that are *queued* but not yet registered.
a list of [[StateDeclaration]]s
Gets a registered state
Given a state or a name, finds and returns the [[StateDeclaration]] from the registry. Note: this does not return states that are *queued* but not yet registered.
Parameter stateOrName
either the name of a state, or a state object.
Parameter base
the base state to use when stateOrName is relative. a registered [[StateDeclaration]] that matched the
stateOrName
, or null if the state isn't registered.
method onStatesChanged
onStatesChanged: (listener: StateRegistryListener) => () => void;
Listen for a State Registry events
Adds a callback that is invoked when states are registered or deregistered with the StateRegistry.
#### Example:
let allStates = registry.get();// Later, invoke deregisterFn() to remove the listenerlet deregisterFn = registry.onStatesChanged((event, states) => {switch(event) {case: 'registered':states.forEach(state => allStates.push(state));break;case: 'deregistered':states.forEach(state => {let idx = allStates.indexOf(state);if (idx !== -1) allStates.splice(idx, 1);});break;}});Parameter listener
a callback function invoked when the registered states changes. The function receives two parameters,
event
andstate
. See [[StateRegistryListener]] a function that deregisters the listener
method register
register: (stateDefinition: _StateDeclaration) => StateObject;
Adds a state to the registry
Registers a [[StateDeclaration]] or queues it for registration.
Note: a state will be queued if the state's parent isn't yet registered.
Parameter stateDefinition
the definition of the state to register.
Returns
the internal [[StateObject]] object. If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]). If the state was only queued, then the object is not fully built.
method root
root: () => StateObject;
Gets the implicit root state
Gets the root of the state tree. The root state is implicitly created by UI-Router. Note: this returns the internal [[StateObject]] representation, not a [[StateDeclaration]]
the root [[StateObject]]
class StateService
class StateService {}
Provides services related to ui-router states.
This API is located at
router.stateService
([[UIRouter.stateService]])
property $current
readonly $current: StateObject;
The current [[StateObject]] (an internal API)
Deprecated
This is a passthrough through to [[UIRouterGlobals.$current]]
property current
readonly current: StateDeclaration;
The current [[StateDeclaration]]
Deprecated
This is a passthrough through to [[UIRouterGlobals.current]]
property params
readonly params: StateParams;
The latest successful state parameters
Deprecated
This is a passthrough through to [[UIRouterGlobals.params]]
property transition
readonly transition: Transition;
The [[Transition]] currently in progress (or null)
Deprecated
This is a passthrough through to [[UIRouterGlobals.transition]]
method defaultErrorHandler
defaultErrorHandler: (handler?: (error: any) => void) => (error: any) => void;
Sets or gets the default [[transitionTo]] error handler.
The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition. This includes errors caused by resolves and transition hooks.
Note: This handler does not receive certain Transition rejections. Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].
The built-in default error handler logs the error to the console.
You can provide your own custom handler.
#### Example:
stateService.defaultErrorHandler(function() {// Do not log transitionTo errors});Parameter handler
a global error handler function
Returns
the current global error handler
method get
get: { (stateOrName: StateOrName, base: StateOrName): StateDeclaration; (stateOrName: StateOrName): StateDeclaration; (): StateDeclaration[];};
Gets a registered [[StateDeclaration]] object
Returns the state declaration object for any specific state, or for all registered states.
Parameter stateOrName
(absolute or relative) If provided, will only get the declaration object for the requested state. If not provided, returns an array of ALL states.
Parameter base
When
stateOrName
is a relative state reference (such as.bar.baz
), the state will be retrieved relative to this state.Returns
a [[StateDeclaration]] object (or array of all registered [[StateDeclaration]] objects.)
Deprecated
use [[StateRegistry.get]]
method go
go: ( to: StateOrName, params?: RawParams, options?: TransitionOptions) => TransitionPromise;
Transition to a different state and/or parameters
Convenience method for transitioning to a new state.
$state.go
calls$state.transitionTo
internally but automatically sets options to{ location: true, inherit: true, relative: router.globals.$current, notify: true }
. This allows you to use either an absolute or relativeto
argument (because ofrelative: router.globals.$current
). It also allows you to specify * only the parameters you'd like to update, while letting unspecified parameters inherit from the current parameter values (because ofinherit: true
).#### Example:
let app = angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.changeState = function () {$state.go('contact.detail');};});Parameter to
Absolute state name, state object, or relative state path (relative to current state).
Some examples:
-
$state.go('contact.detail')
- will go to thecontact.detail
state -$state.go('^')
- will go to the parent state -$state.go('^.sibling')
- if current state ishome.child
, will go to thehome.sibling
state -$state.go('.child.grandchild')
- if current state is home, will go to thehome.child.grandchild
stateParameter params
A map of the parameters that will be sent to the state, will populate $stateParams.
Any parameters that are not specified will be inherited from current parameter values (because of
inherit: true
). This allows, for example, going to a sibling state that shares parameters defined by a parent state.Parameter options
Transition options
Returns
{promise} A promise representing the state of the new transition.
method href
href: ( stateOrName: StateOrName, params?: RawParams, options?: HrefOptions) => string;
Generates a URL for a state and parameters
Returns the url for the given state populated with the given params.
#### Example:
expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");Parameter stateOrName
The state name or state object you'd like to generate a url from.
Parameter params
An object of parameter values to fill the state's required parameters.
Parameter options
Options object. The options are:
Returns
{string} compiled state url
method includes
includes: ( stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions) => boolean;
Checks if the current state *includes* the provided state
A method to determine if the current active state is equal to or is the child of the state stateName. If any params are passed then they will be tested for a match as well. Not all the parameters need to be passed, just the ones you'd like to test for equality.
#### Example when
$state.$current.name === 'contacts.details.item'
// Using partial names$state.includes("contacts"); // returns true$state.includes("contacts.details"); // returns true$state.includes("contacts.details.item"); // returns true$state.includes("contacts.list"); // returns false$state.includes("about"); // returns false#### Glob Examples when
* $state.$current.name === 'contacts.details.item.url'
:$state.includes("*.details.*.*"); // returns true$state.includes("*.details.**"); // returns true$state.includes("**.item.**"); // returns true$state.includes("*.details.item.url"); // returns true$state.includes("*.details.*.url"); // returns true$state.includes("*.details.*"); // returns false$state.includes("item.**"); // returns falseParameter stateOrName
A partial name, relative name, glob pattern, or state object to be searched for within the current state name.
Parameter params
A param object, e.g.
{sectionId: section.id}
, that you'd like to test against the current active state.Parameter options
An options object. The options are: -
relative
: IfstateOrName
is a relative state name andoptions.relative
is set, .is will test relative tooptions.relative
state (or name).Returns
{boolean} Returns true if it does include the state
method is
is: ( stateOrName: StateOrName, params?: RawParams, options?: { relative?: StateOrName }) => boolean;
Checks if the current state *is* the provided state
Similar to [[includes]] but only checks for the full state name. If params is supplied then it will be tested for strict equality against the current active params object, so all params must match with none missing and no extras.
#### Example:
$state.$current.name = 'contacts.details.item';// absolute name$state.is('contact.details.item'); // returns true$state.is(contactDetailItemStateObject); // returns true// relative name (. and ^), typically from a template // E.g. from the 'contacts.details' template
<div ng-class="{highlighted: $state.is('.item')}">Item</div>Parameter stateOrName
The state name (absolute or relative) or state object you'd like to check.
Parameter params
A param object, e.g.
{sectionId: section.id}
, that you'd like to test against the current active state.Parameter options
An options object. The options are: -
relative
: IfstateOrName
is a relative state name andoptions.relative
is set, .is will test relative tooptions.relative
state (or name).Returns
Returns true if it is the state.
method lazyLoad
lazyLoad: ( stateOrName: StateOrName, transition?: Transition) => Promise<LazyLoadResult>;
Lazy loads a state
Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.
Parameter stateOrName
the state that should be lazy loaded
Parameter transition
the optional Transition context to use (if the lazyLoad function requires an injector, etc) Note: If no transition is provided, a noop transition is created using the from the current state to the current state. This noop transition is not actually run.
Returns
a promise to lazy load
method onInvalid
onInvalid: (callback: OnInvalidCallback) => Function;
Registers an Invalid State handler
Registers a [[OnInvalidCallback]] function to be invoked when [[StateService.transitionTo]] has been called with an invalid state reference parameter
Example:
stateService.onInvalid(function(to, from, injector) {if (to.name() === 'foo') {let lazyLoader = injector.get('LazyLoadService');return lazyLoader.load('foo').then(() => stateService.target('foo'));}});Parameter callback
invoked when the toState is invalid This function receives the (invalid) toState, the fromState, and an injector. The function may optionally return a [[TargetState]] or a Promise for a TargetState. If one is returned, it is treated as a redirect.
Returns
a function which deregisters the callback
method reload
reload: (reloadState?: StateOrName) => Promise<StateObject>;
Reloads the current state
A method that force reloads the current state, or a partial state hierarchy. All resolves are re-resolved, and components reinstantiated.
#### Example:
let app angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.reload = function(){$state.reload();}});Note:
reload()
is just an alias for:$state.transitionTo($state.current, $state.params, {reload: true, inherit: false});Parameter reloadState
A state name or a state object. If present, this state and all its children will be reloaded, but ancestors will not reload.
#### Example:
//assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'//and current state is 'contacts.detail.item'let app angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.reload = function(){//will reload 'contact.detail' and nested 'contact.detail.item' states$state.reload('contact.detail');}});Returns
A promise representing the state of the new transition. See [[StateService.go]]
method target
target: ( identifier: StateOrName, params?: RawParams, options?: TransitionOptions) => TargetState;
Creates a [[TargetState]]
This is a factory method for creating a TargetState
This may be returned from a Transition Hook to redirect a transition, for example.
method transitionTo
transitionTo: ( to: StateOrName, toParams?: RawParams, options?: TransitionOptions) => TransitionPromise;
Low-level method for transitioning to a new state.
The [[go]] method (which uses
transitionTo
internally) is recommended in most situations.#### Example:
let app = angular.module('app', ['ui.router']);app.controller('ctrl', function ($scope, $state) {$scope.changeState = function () {$state.transitionTo('contact.detail');};});Parameter to
State name or state object.
Parameter toParams
A map of the parameters that will be sent to the state, will populate $stateParams.
Parameter options
Transition options
Returns
A promise representing the state of the new transition. See [[go]]
class TargetState
class TargetState {}
Encapsulate the target (destination) state/params/options of a [[Transition]].
This class is frequently used to redirect a transition to a new destination.
See:
- [[HookResult]] - [[TransitionHookFn]] - [[TransitionService.onStart]]
To create a
TargetState
, use [[StateService.target]].---
This class wraps:
1) an identifier for a state 2) a set of parameters 3) and transition options 4) the registered state object (the [[StateDeclaration]])
Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string). The
TargetState
class normalizes those options.A
TargetState
may be valid (the state being targeted exists in the registry) or invalid (the state being targeted is not registered).
property isDef
static isDef: (obj: any) => obj is TargetStateDef;
Returns true if the object has a state property that might be a state or state name
method $state
$state: () => StateObject;
The internal state object (if it was found)
method error
error: () => string;
If the object is invalid, returns the reason why
method exists
exists: () => boolean;
True if the target state was found
method identifier
identifier: () => StateOrName;
The identifier used when creating this TargetState
method name
name: () => string;
The name of the state this object targets
method options
options: () => TransitionOptions;
The target options
method params
params: () => RawParams;
The target parameter values
method state
state: () => StateDeclaration;
The internal state declaration (if it was found)
method toString
toString: () => string;
method valid
valid: () => boolean;
True if the object is valid
method withOptions
withOptions: (options: TransitionOptions, replace?: boolean) => TargetState;
Returns a copy of this TargetState, using the specified Transition Options.
Parameter options
the new options to use
Parameter replace
When false (default) the new options will be merged with the current options. When true the options will be used instead of the current options.
method withParams
withParams: (params: RawParams, replace?: boolean) => TargetState;
Returns a copy of this TargetState, using the specified parameter values.
Parameter params
the new parameter values to use
Parameter replace
When false (default) the new parameter values will be merged with the current values. When true the parameter values will be used instead of the current values.
method withState
withState: (state: StateOrName) => TargetState;
Returns a copy of this TargetState which targets a different state. The new TargetState has the same parameter values and transition options.
Parameter state
The new state that should be targeted
class Trace
class Trace {}
Prints UI-Router Transition trace information to the console.
method disable
disable: (...categories: (Category | string | number)[]) => any;
Disables a trace [[Category]]
trace.disable("VIEWCONFIG");Parameter categories
categories to disable. If
categories
is omitted, all categories are disabled. Also takes strings (category name) or ordinal (category position)
method enable
enable: (...categories: (Category | string | number)[]) => any;
Enables a trace [[Category]]
trace.enable("TRANSITION");Parameter categories
categories to enable. If
categories
is omitted, all categories are enabled. Also takes strings (category name) or ordinal (category position)
method enabled
enabled: (category: Category | string | number) => boolean;
Retrieves the enabled stateus of a [[Category]]
trace.enabled("VIEWCONFIG"); // true or falseReturns
boolean true if the category is enabled
class Transition
class Transition implements IHookRegistry {}
Represents a transition between two states.
When navigating to a state, we are transitioning **from** the current state **to** the new state.
This object contains all contextual information about the to/from states, parameters, resolves. It has information about all states being entered and exited as a result of the transition.
property $id
$id: number;
A unique identifier for the transition.
This is an auto incrementing integer, starting from
0
.
property isActive
isActive: () => boolean;
Checks if this transition is currently active/running.
property promise
promise: Promise<any>;
This promise is resolved or rejected based on the outcome of the Transition.
When the transition is successful, the promise is resolved When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error
property router
router: UIRouter;
A reference to the [[UIRouter]] instance
This reference can be used to access the router services, such as the [[StateService]]
property success
success: boolean;
A boolean which indicates if the transition was successful
After a successful transition, this value is set to true. After an unsuccessful transition, this value is set to false.
The value will be undefined if the transition is not complete
method abort
abort: () => void;
Aborts this transition
Imperative API to abort a Transition. This only applies to Transitions that are not yet complete.
method addResolvable
addResolvable: ( resolvable: Resolvable | ResolvableLiteral, state?: StateOrName) => void;
Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.
Allows a transition hook to dynamically add a Resolvable to this Transition.
Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).
If a
state
argument is provided, the Resolvable is processed when that state is being entered. If nostate
is provided then the root state is used. If the givenstate
has already been entered, the Resolvable is processed when any child state is entered. If no child states will be entered, the Resolvable is processed during theonFinish
phase of the Transition.The
state
argument also scopes the resolved data. The resolved data is available from the injector for thatstate
and any children states.#### Example:
transitionService.onBefore({}, transition => {transition.addResolvable({token: 'myResolve',deps: ['MyService'],resolveFn: myService => myService.getData()});});Parameter resolvable
a [[ResolvableLiteral]] object (or a [[Resolvable]])
Parameter state
the state in the "to path" which should receive the new resolve (otherwise, the root state)
method dynamic
dynamic: () => boolean;
Returns true if the transition is dynamic.
A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.
Returns
true if the Transition is dynamic
method entering
entering: () => StateDeclaration[];
Gets the states being entered.
Returns
an array of states that will be entered during this transition.
method error
error: () => Rejection;
The Transition error reason.
If the transition is invalid (and could not be run), returns the reason the transition is invalid. If the transition was valid and ran, but was not successful, returns the reason the transition failed.
Returns
a transition rejection explaining why the transition is invalid, or the reason the transition failed.
method exiting
exiting: () => StateDeclaration[];
Gets the states being exited.
Returns
an array of states that will be exited during this transition.
method from
from: () => StateDeclaration;
Returns the "from state"
Returns the state that the transition is coming *from*.
Returns
The state declaration object for the Transition's ("from state").
method getResolveTokens
getResolveTokens: (pathname?: string) => any[];
Gets all available resolve tokens (keys)
This method can be used in conjunction with [[injector]] to inspect the resolve values available to the Transition.
This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states in the Transition's [[TreeChanges.to]] path.
#### Example: This example logs all resolve values
let tokens = trans.getResolveTokens();tokens.forEach(token => console.log(token + " = " + trans.injector().get(token)));#### Example: This example creates promises for each resolve value. This triggers fetches of resolves (if any have not yet been fetched). When all promises have all settled, it logs the resolve values.
let tokens = trans.getResolveTokens();let promise = tokens.map(token => trans.injector().getAsync(token));Promise.all(promises).then(values => console.log("Resolved values: " + values));Note: Angular 1 users whould use
$q.all()
Parameter pathname
resolve context's path name (e.g.,
to