【问题标题】:Angular 2 Router Directly Accessing URL [duplicate]Angular 2路由器直接访问URL [重复]
【发布时间】:2016-02-24 01:21:45
【问题描述】:

我有我的main.component.ts 代码:
它的位置是:root/

import {Component, OnInit, OnChanges, IterableDiffers} from 'angular2/core';
import {TypeService} from './type/type.service';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {Router} from 'angular2/router';

@Component({
    selector: 'my-app',
    providers: [],
    directives: [ROUTER_DIRECTIVES],
    template: `
      <a [routerLink]="['Type']">Type</a>
      <router-outlet></router-outlet>
    `
})

@RouteConfig([
  {path:'/type', name: 'Type', component: TypeService}
])

export class AppComponent{
  constructor(private _router: Router){}
}

然后我有我的type.component.ts 代码:
它的位置是:root/type

import {Component, OnInit} from 'angular2/core';
import {DirectoryComponent} from '../main/main.component';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {Router} from 'angular2/router';
import {AppComponent} from '../app.component';
import {Http} from 'angular2/http';

@Component({
  selector: 'type',
  directives: [ROUTER_DIRECTIVES],
  template: `<h1>hi</h1>`
})

export class TypeService{

  constructor(
    private _router: Router) {}
  }

当我在主应用程序中单击类型链接时,它会将我带到 root/type 并加载类型组件。但是,如果我按重新加载它会给我一个 Not Found 错误。

我该如何做才能直接通过 url 访问组件?

【问题讨论】:

    标签: routing angular


    【解决方案1】:

    当找不到请求的 url 时,您需要配置服务器以提供主文件(通常为 index.html)。根据您使用的服务器,它可能是.htaccess 文件、中间件、路由配置等。SO 上有很多类似的问题,请尝试为您的具体情况寻找答案...

    【讨论】:

    【解决方案2】:

    我使用了 HashLocationStrategy 来修复它。

    https://angular.io/docs/ts/latest/api/router/HashLocationStrategy-class.html

    在 main.ts 中:

    import {bootstrap}    from 'angular2/platform/browser'
    import {AppComponent} from './app.component'
    import {HTTP_PROVIDERS} from 'angular2/http';
    import {ROUTER_PROVIDERS,
      LocationStrategy,
      HashLocationStrategy} from 'angular2/router';
    import {provide} from 'angular2/core';
    
    bootstrap(AppComponent, [
      HTTP_PROVIDERS,
      ROUTER_PROVIDERS,
      provide(LocationStrategy, {useClass: HashLocationStrategy})
    ]);
    

    然后转到 root/#/type,它会将我带到我的类型组件。

    【讨论】:

    • 试试这个而不是其他的。它对我有用,不确定,但似乎正在进行中。 @RouteConfig([ { path: '/**', redirectTo: ['MycmpnameCmp'] }, ... } ])github.com/angular/angular/issues/4055
    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多