2016-05-15 57 views
0

我已經使用Angular2構建SPA。我想知道如何使用ES5重定向。如果我使用window.location,那麼它會重新加載整個頁面。我只是想要更換組件。Angular2使用JavaScript重定向?

好像我需要使用ng.router.Redirect,但是當我稱它沒有任何反應時。

回答

1

爲什麼要使用JavaScript如果角提供導航方法本身,我不知道有關es5,但是我在打字稿中使用router.navigate(['routeName'])。只需嘗試使用路由,您可以只更改組件而不是加載整個頁面。

don't forget to instantiate router in the constructor like this.

export class AppComponent implements OnInit { 
    constructor(private router: Router) {} 

    ngOnInit() { 
    this.router.navigate(['/yourRouteName']); 
    } 
} 

更多信息看這裏https://angular.io/docs/ts/latest/guide/router.html

更新ES5

app.AppComponent = ng.core 
    .Component({ 
     selector: 'the-app', 
     template: ` 
      <h1>App!!!</h1> 
      <a [routerLink]="['Login']">Login</a> 
      <a [routerLink]="['ABC']">ABC</a> 
      <router-outlet></router-outlet> 
     `, 
     directives:[ 
      ng.router.ROUTER_DIRECTIVES 
     ] 
    }) 
    .Class({ 
     constructor: [ng.router.Route, function(_router) { 
      this._router = _router; // use for navigation, etc 
      this._router.navigate(['RouteName']) // For navigation ot another component 
     }] 
    }); 
app.AppComponent = ng.router 
    .RouteConfig([ 
     { path: '/', component:app.LoginCOmponent, name:'Login' }, 
     { path: '/children', component:app.xyz, name:'xyz' } 
    ])(app.AppComponent); 

我沒有帶試過,但最有可能這一個戈納工作。

+0

我不知道TypeScript。我需要ES5代碼。 –

+0

我得到這個錯誤'錯誤:未捕獲(承諾):沒有供應商的路線! (class2 - > Route)'。似乎你錯過了路由器服務的提供者。 –

+0

你有沒有在引導你的應用程序時在index.html和router_providers中提供路由器文件 –