Angular 2 router sin base href set


Estoy recibiendo un error y no puedo encontrar por qué. Aquí está el error:

EXCEPTION: Error during instantiation of LocationStrategy! (RouterOutlet -> Router -> Location -> LocationStrategy).
    angular2.dev.js:23514 EXCEPTION: Error during instantiation of LocationStrategy! (RouterOutlet -> Router -> Location -> LocationStrategy).BrowserDomAdapter.logError @ angular2.dev.js:23514BrowserDomAdapter.logGroup @ angular2.dev.js:23525ExceptionHandler.call @ angular2.dev.js:1145(anonymous function) @ angular2.dev.js:14801NgZone._notifyOnError @ angular2.dev.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
    angular2.dev.js:23514 ORIGINAL EXCEPTION: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.BrowserDomAdapter.logError @ angular2.dev.js:23514ExceptionHandler.call @ angular2.dev.js:1154(anonymous function) @ angular2.dev.js:14801NgZone._notifyOnError @ angular2.dev.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
    angular2.dev.js:23514 ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23514ExceptionHandler.call @ angular2.dev.js:1157(anonymous function) @ angular2.dev.js:14801NgZone._notifyOnError @ angular2.dev.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
    angular2.dev.js:23514 Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.
        at new BaseException (angular2.dev.js:8080)
        at new PathLocationStrategy (router.dev.js:1203)
        at angular2.dev.js:1380
        at Injector._instantiate (angular2.dev.js:11923)
        at Injector._instantiateProvider (angular2.dev.js:11859)
        at Injector._new (angular2.dev.js:11849)
        at InjectorDynamicStrategy.getObjByKeyId (angular2.dev.js:11733)
        at Injector._getByKeyDefault (angular2.dev.js:12048)
        at Injector._getByKey (angular2.dev.js:12002)
        at Injector._getByDependency (angular2.dev.js:11990)

¿Alguien sabe por qué el router está lanzando esto? Estoy usando angular2 beta

Aquí está mi código:

import {Component} from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';
import {LoginComponent} from './pages/login/login.component';
import {DashboardComponent} from './pages/dashboard/dashboard.component';
@Component({
    selector: 'app',
    directives:[ROUTER_DIRECTIVES],
    template:`
        <div class="wrapper">
            <router-outlet></router-outlet>
        </div>`
})
@RouteConfig([
    { path: '/',redirectTo: '/dashboard' },
    { path: '/login',name:'login',component: LoginComponent },
    { path: '/dashboard',name:'dashboard',component: DashboardComponent,}
])
export class AppComponent {
}
Author: Günter Zöchbauer, 2015-12-30

6 answers

Https://angular.io/docs/ts/latest/guide/router.html

Agregue el elemento base justo después de la etiqueta <head>. Si la carpeta app es la raíz de la aplicación, como lo es para nuestra aplicación, establezca el valor href exactamente como se muestra aquí.

El <base href="/"> le dice al enrutador Angular cuál es la parte estática de la URL. El router solo modifica la parte restante de la URL.

<head>
  <base href="/">
  ...
</head>

Alternativamente añadir

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

En tu bootstrap.

En versiones anteriores las importaciones tenían que ser como

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

Véase también Ubicación y HashLocationStrategy dejaron de funcionar en beta.16

 273
Author: Günter Zöchbauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:57

Me había enfrentado a un problema similar con Angular4 y Jasmine pruebas unitarias; a continuación dada solución funcionó para mí

Añadir la siguiente declaración de importación

import { APP_BASE_HREF } from '@angular/common';

Agregue la siguiente instrucción para la configuración del banco de pruebas:

TestBed.configureTestingModule({
    providers: [
        { provide: APP_BASE_HREF, useValue : '/' }
    ]
})
 28
Author: Dilip Nannaware,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-20 17:49:13

Desde 2.0 beta:)

import { APP_BASE_HREF } from 'angular2/platform/common';
 8
Author: fireaxe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-12 13:58:50

También puede usar la navegación basada en hash incluyendo lo siguiente en la aplicación.módulo.ts

import { LocationStrategy, HashLocationStrategy } from '@angular/common';

Y añadiendo lo siguiente al @ NgModule ({... })

@NgModule({
  ...
  providers:    [
      ProductService, {
          provide: LocationStrategy, useClass: HashLocationStrategy
      }
  ],
  ...
})

Desarrollo Angular 2 con TypeScript

"HashLocationStrategy-Se agrega un signo hash (#) a la URL, y el segmento URL después del hash identifica de forma única la ruta que se utilizará como fragmento de página web. Esta estrategia funciona con todos los navegadores, incluidos los antiguos."

Extracto De: Yakov Fain Anton Moiseev. "Angular 2 Desarrollo con TypeScript."

 7
Author: Lionel Morrison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 01:10:35

Con angular 4 puede solucionar este problema actualizando la aplicación .módulo.ts archive como sigue:

Agregue la declaración de importación en la parte superior de la siguiente manera:

import {APP_BASE_HREF} from '@angular/common';

Y añadir debajo de la línea dentro de @NgModule

providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]

Reff: https://angular.io/api/common/APP_BASE_HREF

 3
Author: Suresh Kamrushi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-28 12:21:39

Es solo que agregue el código debajo del índice.html head tag

   <html>
    <head>
     <base href="/">
      ...

Eso funcionó como un encanto para mí.

 1
Author: naram kiran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-12 03:20:10