From 011fab37af626535c1d5af7091d72e27d93f4391 Mon Sep 17 00:00:00 2001 From: Brian Ford Date: Fri, 17 Jul 2015 12:14:48 -0700 Subject: [PATCH] fix(router): improve error for missing base href Closes #3096 --- modules/angular2/src/router/location.ts | 11 +++++++++-- modules/angular2/test/router/location_spec.ts | 8 ++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/modules/angular2/src/router/location.ts b/modules/angular2/src/router/location.ts index 663881ab7a..2f78f7198e 100644 --- a/modules/angular2/src/router/location.ts +++ b/modules/angular2/src/router/location.ts @@ -1,6 +1,7 @@ import {LocationStrategy} from './location_strategy'; import {StringWrapper, isPresent, CONST_EXPR} from 'angular2/src/facade/lang'; import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; +import {BaseException, isBlank} from 'angular2/src/facade/lang'; import {OpaqueToken, Injectable, Optional, Inject} from 'angular2/di'; export const appBaseHrefToken: OpaqueToken = CONST_EXPR(new OpaqueToken('locationHrefToken')); @@ -22,8 +23,14 @@ export class Location { constructor(public _platformStrategy: LocationStrategy, @Optional() @Inject(appBaseHrefToken) href?: string) { - this._baseHref = stripTrailingSlash( - stripIndexHtml(isPresent(href) ? href : this._platformStrategy.getBaseHref())); + var browserBaseHref = isPresent(href) ? href : this._platformStrategy.getBaseHref(); + + if (isBlank(browserBaseHref)) { + throw new BaseException( + `No base href set. Either provide a binding to "appBaseHrefToken" or add a base element.`); + } + + this._baseHref = stripTrailingSlash(stripIndexHtml(browserBaseHref)); this._platformStrategy.onPopState((_) => this._onPopState(_)); } diff --git a/modules/angular2/test/router/location_spec.ts b/modules/angular2/test/router/location_spec.ts index f92e6f2d23..e603e7199e 100644 --- a/modules/angular2/test/router/location_spec.ts +++ b/modules/angular2/test/router/location_spec.ts @@ -75,5 +75,13 @@ export function main() { location.go('user/btford'); expect(locationStrategy.path()).toEqual('/my/custom/href/user/btford'); }); + + it('should throw when no base href is provided', () => { + var locationStrategy = new MockLocationStrategy(); + locationStrategy.internalBaseHref = null; + expect(() => new Location(locationStrategy)) + .toThrowError( + `No base href set. Either provide a binding to "appBaseHrefToken" or add a base element.`); + }); }); }