2016-10-15 4 views
3

경로 2에 상관없이 페이지로드시 기본 경로로 이동하도록 Angular 2 애플리케이션을 설정하려고하지만 경로가 작동하지 않는 것 같습니다.앱로드시 특정 페이지로 강제 리디렉션

로직을 내 app-component의 ngOnInit에 추가하여 내 홈 경로로 리디렉션하지만 무시됩니다.

import {Component, OnInit} from '@angular/core'; 
import {Router} from "@angular/router"; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppComponent implements OnInit { 

    constructor(private router: Router) {} 

    closeApplication() { 
    electron.ipcRenderer.send('close-app'); 
    } 

    ngOnInit() { 
    console.log('I am being run.'); 
    this.router.navigate(['']); 
    } 

} 

는 여기에 몇 가지 상황에 맞는, 내가 사용자가 기본 페이지에서 응용 프로그램을 시작하면 환상적인 노력하고 선형 사용자 흐름을 가진 전자 응용 프로그램을 만드는 오전 내 라우팅 설정

import {LoginComponent} from "./login/login.component"; 
import {HomeComponent} from "./home/home.component"; 
import {AuthGuard} from "./shared/security/auth.guard"; 
import {RegisterComponent} from "./register/register.component"; 
import {ListingComponent} from "./listing/listing.component"; 
import {RedirectGuard} from "./shared/security/redirect.guard"; 
import {WelcomeComponent } from "./welcome/welcome.component"; 

export const routerConfig = [ 
    { path: 'login', component: LoginComponent, canActivate: [RedirectGuard] }, 
    { path: 'register', component: RegisterComponent, canActivate: [RedirectGuard] }, 
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard], 
    children: [ 
     { 
     path: '', 
     component: ListingComponent 
     }, 
     { 
     path: 'listing/:id', 
     component: ListingComponent 
     } 
    ] 
    }, 
    { path: '', component: WelcomeComponent }, 
    { path: '**', component: HomeComponent }, 
]; 

입니다. 3 페이지를 새로 고치고 새로 고치면 전체 응용 프로그램 상태가 모두 엉망입니다. 나는 상태를 유지하기 위해 데이터베이스를 사용하지 않고 있으며 로컬 저장소에 저장하는 것이 최종 목표에 너무 많은 부담이라고 생각합니다.

건배!

+0

라우팅 구성을 게시하십시오. –

+0

자, 자. 나는 그것을 추가했다 – Luca

답변

1

다음 아키텍처를 프로젝트에로드하여 redirect.component을 생성하여 코스를로드 한 후로드해야하는 위치를 해결했습니다. 다음은 초소형 버전입니다.

import { Component, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-redirect', 
    template: `` 
}) 
export class RedirectComponent implements OnInit { 
    private goDownPathOne: boolean = true; 

    constructor() { } 

    ngOnInit() { 
     if(goDownPathOne) 
      this.router.navigate('path1'); 
     else 
      this.router.navigate('path2'); 
    } 

} 

그런 다음 내 app.routing에서 나는 다음과 같습니다

응용 프로그램의 부하에 따라서
const COURSE_ROUTES: Routes = [ 
    // Home/Menu Screen 
    { path: '', component: RedirectComponent }, 
    // Default Routes 
    { path: 'screen', redirectTo: '/', pathMatch: 'full' }, 
    { path: 'text', redirectTo: '/', pathMatch: 'full' }, 
    { path: 'activity', redirectTo: '/', pathMatch: 'full' }, 
    { path: '**', redirectTo: '/', pathMatch: 'full' } 

]; 

export const courseRouting: ModuleWithProviders = RouterModule.forRoot(COURSE_ROUTES); 

, 그것은 항상 우리가 제공하는 데이터에 어디로 가야 다음 결정하는 RedirectComponent에 간다 - 내 경우 I 그것을 데이터베이스에서 끌어 내렸다. 그러나 이것이 최적의 접근 방법인지는 확실하지 않지만, defiinitely works!

0

router configuration을 올바르게 설정하십시오. 당신의 경로를 구성 할 때 당신은 또한 설정 redirectswildcards를 사용할 수 있습니다

{path: '**', redirectTo: 'your-defaultPath', pathMatch:'full'}

가 angular2 라우터에 대한 추가 정보를 원하시면 전체 routing docs을 확인합니다.

다음은 '집'및 '기타'경로가있는 간단한 예입니다. 빈 경로는 '집'으로 리디렉션되고 일치하지 않는 경로는 집으로 리디렉션됩니다.

import {BrowserModule} from '@angular/platform-browser' 
import {Component, NgModule} from '@angular/core' 
import {RouterModule} from '@angular/router'; 

@Component({selector: 'app', template: 'App Shell<br> <router-outlet></router-outlet>'}) 
export class AppComponent {} 

@Component({selector:'home', template:'Home component'}) 
export class HomeComponent {} 

@Component({selector:'other', template:'Other component'}) 
export class OtherComponent {} 

@NgModule({ 
    imports: [ 
    BrowserModule, 
    RouterModule.forRoot([ 
     {path:'home', component: HomeComponent}, 
     {path:'other', component: OtherComponent}, 
     {path:'', redirectTo:'home', pathMatch:'full'}, 
     {path:'**', redirectTo:'home'} 
    ], {enableTracing:true}) 
    ], 
    declarations: [AppComponent, HomeComponent, OtherComponent], 
    bootstrap: [AppComponent] 
}) 
export class AppModule {} 

탐색에 대한 자세한 정보를 얻으려면 enableTracing 옵션을 true로 설정합니다.

+0

나는 이미 노선 설치가있다. 나는 그것을 위로 덧붙였다. 당신의 제안을'**'경로에 추가했을 때, 어플리케이션은 똑같이 행동했습니다. 내가 리다이렉트하고 싶었던 경로 (집과 그 아이들)에 올리려고했을 때,이 페이지에 대한 라우트 변경에 대해 "환영"으로 리디렉션했다. – Luca

+0

간단한 예제를 추가했습니다. 도움이되기를 바랍니다. ngOnInit에서 리디렉션을 수행하지 않는 것이 좋습니다. 모든 경로 일치 및 리디렉션은 라우터 구성에 배치해야합니다. – dinony

+0

이것이 내 문제를 해결했다고 생각하지 않습니다. 특정 경로로 연결되는 경로에서 응용 프로그램을 새로 고칩니다. 내가 너에게 제안을 구현할 때, 내가 그걸 똑같은 길로 데려 올 때 새로 고침 할 때. – Luca

관련 문제