Угловой маршрутизатор 2 отсутствие базового набора href
Я получаю сообщение об ошибке, и не могу найти почему. Вот ошибка:
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)
кто-нибудь знает, почему маршрутизатор бросать? Я использую angular2 beta
вот мой код:
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 {
}
6 ответов:
https://angular.io/docs/ts/latest/guide/router.html
добавить Базовый элемент сразу после
<head>
тег. Еслиapp
папка-это корень приложения, как и для нашего приложения, установитеhref
стоимостью ровно как показано здесь.The
<base href="/">
сообщает угловому маршрутизатору, что такое статическая часть URL. Маршрутизатор изменяет только оставшуюся часть URL-АДРЕС.<head> <base href="/"> ... </head>
как вариант добавить
> = Angular2 RC.6
import {APP_BASE_HREF} from '@angular/common'; @NgModule({ declarations: [AppComponent], imports: [routing /* or RouterModule */], providers: [{provide: APP_BASE_HREF, useValue : '/' }] ]);
в свой загрузчик.
в старых версиях импорт должен быть как
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';
>= бета.17
import {APP_BASE_HREF} from 'angular2/platform/common';
Смотрите также Location и HashLocationStrategy перестали работать в бета-версии.16
я столкнулся с аналогичной проблемой с angular4 и модульными тестами Jasmine; ниже приведенное решение работало для меня
добавить ниже оператор импорта
import { APP_BASE_HREF } from '@angular/common';
добавить ниже заявление для конфигурации испытательного стенда:
TestBed.configureTestingModule({ providers: [ { provide: APP_BASE_HREF, useValue : '/' } ] })
вы также можете использовать навигацию на основе хэша, включив в приложение следующее.модуль.ТС
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
и добавив следующее в @NgModule ({ ... })
@NgModule({ ... providers: [ ProductService, { provide: LocationStrategy, useClass: HashLocationStrategy } ], ... })
" HashLocationStrategy-знак хэша (#) добавляется к URL, и сегмент URL после хэша однозначно определяет маршрут, который будет использоваться в качестве фрагмента веб-страницы. Эта стратегия работает со всеми браузерами, включая старые."
Отрывок Из: Яков Файн Антон Моисеев. "Угловая 2 Разработка с машинописным текстом."
С угловой 4 Вы можете исправить эту проблему, обновив приложение.модуль.ТС файл выглядит следующим образом:
добавить оператор импорта в верхней части, как показано ниже:
import {APP_BASE_HREF} from '@angular/common';
и добавить ниже строку внутри
@NgModule
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]