Angular 2路由器没有设置基本href

227

我遇到了一个错误,但不知道原因。这是错误信息:

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 {
}
8个回答

412

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

<head> 标签之后添加基础元素。如果 app 文件夹是应用程序根目录(本应用程序就是这样),请将 href 值设置为此处所示的值。

<base href="/"> 会告诉 Angular 路由器 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 : '/' }]
]); 

在您的Bootstrap中。

在旧版本中,导入方式必须如下所示

< Angular2 RC.6

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

< RC.0

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

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

->

>= beta.17

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

另请参阅beta.16中Location和HashLocationStrategy不再工作的问题


3
第二种方法的简单示例:bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue : '/'})]); 注:该语句为AngularJS应用程序中的代码,其中包含了启动组件"AppComponent"和提供路由服务的"ROUTER_PROVIDERS",以及提供根URL路径的服务"APP_BASE_HREF"。 - malloc4k
2
我不得不添加导入行 import {provide} from 'angular2/core'; 才能使用 provide。 - CorayThan
2
我必须导入行import {APP_BASE_HREF} from 'angular2/router'; - jimmystormig
1
我的项目中有填充图案的SVG元素。当文件中设置了<base href="/" />时(无论图案中的图像路径如何指定为"/""./""#" 或其他基本路径),这些图像在Firefox中从未显示过。最终唯一有效的解决方案是使用APP_BASE_HREF。真是救命稻草! - ConnorsFan
1
稍等,但是<base href="/">正是Angular构建无法通过打开本地文件夹中的index.html来打开的原因(没有Web服务器)...我不明白为什么Angular需要这个base href。 - Dmitry Gusarov
显示剩余18条评论

38

我曾遇到过 Angular4 和 Jasmine 单元测试类似的问题;以下给出的解决方案对我起了作用

添加以下导入语句

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

在TestBed配置中添加以下语句:

TestBed.configureTestingModule({
    providers: [
        { provide: APP_BASE_HREF, useValue : '/' }
    ]
})

15

修复 Angular 7、8 的问题在 app.module.ts 中。

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

@NgModule 中添加

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


1
当我尝试加载一个带有路由依赖的 Angular Storybook 组件时,我遇到了这个错误。解决该错误后,组件成功加载! - Arpan Banerjee

12

您也可以通过在app.module.ts中包含以下内容来使用基于哈希的导航

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

通过将以下内容添加到 @NgModule({ ... }) 中:

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

使用TypeScript进行Angular 2开发

“HashLocationStrategy——在URL后添加一个#符号,#符号后面的URL片段唯一标识要用作网页片段的路由。这个策略适用于所有浏览器,包括旧版浏览器。”

摘自:Yakov Fain Anton Moiseev著,《使用TypeScript进行Angular 2开发》。


谢谢Lionel!这太棒了,解决了我使用APP_BASE_HREF解决方案时遇到的问题,当使用像“product /:id”这样的URL参数时会失败。谢谢! - Stokely

8
自2.0 beta版本以来 :)
import { APP_BASE_HREF } from 'angular2/platform/common';

从Rc6开始,这一切都在提供者中了:https://angular.io/docs/ts/latest/api/common/index/APP_BASE_HREF-let.html - Mark Kenny
1
这个对我很有帮助,当我的Karma规范失败并显示“Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.”的错误信息时。 - AlignedDev

7
只需要在index.html的头部标签中添加以下代码即可。
   <html>
    <head>
     <base href="/">
      ...

这对我来说非常有效。

6

使用 Angular 4,您可以通过更新 app.module.ts 文件来解决此问题:

请在顶部添加以下导入语句:

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

接下来在 @NgModule 内添加以下代码:

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

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


为什么useValue需要是'/my/app'? - Dilip Nannaware

2

请检查您的index.html文件。 如果您不小心删除了以下部分,请将其包含在文件中,问题就会得到解决。

原始答案:Original Answer

<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接