2016-02-24 139 views
4

我有我main.component.ts代碼:
它的位置是:root/角2路由器直接訪問URL

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並加載類型組件。但是,如果我按下重新加載它給我一個未找到錯誤。

我該怎麼做才能直接通過url訪問組件?

回答

2

如果找不到請求的URL,則需要配置服務器以便爲主文件(通常爲index.html)提供服務。根據你使用的服務器,它可能是.htaccess文件,中間件,路由配置等有很多類似的問題,所以試圖找到你的具體情況的答案...

+0

有沒有像在其他角度1.x? – Gary

+0

@Gary我正在使用'{path:'/:unknown',redirectTo:['/ Root']}',不知道是否有更好的方法... – Sasxa

+0

http://stackoverflow.com/questions/34381438/equivalent-of-angular-1-otherwise-route-in-angular-2 https://github.com/angular/angular/issues/4055讓我正式回答這個問題。我自己在這個問題上陷入困境。 – Gary

0

我用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}) 
]); 

然後去根/#/鍵入它帶我到我喜歡的類型組件。

+0

試試這個,而不是其他。它適用於我,不知道,但似乎正在進行中的工作。 '@RouteConfig([{ 路徑: '/ **',redirectTo:[ 'MycmpnameCmp']},... } ])' https://github.com/angular/angular/issues/4055 – Gary