João Maia
João Maia

Reputation: 13

Angular2 Child Component browser refresh redirects to Parent Component

My application has 2 Parent components.

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

@RouteConfig([
    { path : '/router/...', name:'Router', component: RoutingComponent, useAsDefault: true},
    { path : '/login', name:'Login', component: LoginComponent }
])

export class AppComponent implements OnInit{

    constructor(
        private _router: Router
    ){}

    ngOnInit(){
        if(localStorage.getItem("user")=== null) {
            this._router.navigate(['Login']);
        }
        else{
            console.log(" APP COMPONENT");
            this._router.navigate(['/Router', 'RegisterClient']);
        }
    }
}

When the user is logged in, the app redirects to the child component of Router, called RegisterClient, as it is the main page of the application. If the user is not logged in, the app redirects to LoginComponent.

My Router component has many child component's

@Component({
selector:'router',
directives: [ROUTER_DIRECTIVES],
templateUrl: 'app/routing.component.html',
providers: [AuthenticationService, MessageService]

})

@RouteConfig([
{ path : 'registerClient', name:'RegisterClient', component: RegisterClientComponent},
{ path : 'searchClient', name:'SearchClient', component: SearchClientComponent},
{ path : 'updateClient/:id', name:'UpdateClient', component: UpdateClientComponent},
{ path : 'registerMerchandise', name:'RegistMerc', component: RegisterMercComponent},
{ path : 'searchMerchandise', name:'SearchMerc', component: SearchMerchandiseComponent},
{ path : 'updateMerchandise/:id', name:'UpdateMerc', component: UpdateMercComponent},
{ path : 'registMaterial', name:'RegistMaterial', component: RegisterMaterialComponent},
{ path : 'searchMaterial', name:'SearchMaterial', component: SearchMaterialComponent},
{ path : 'updateMaterial/:id', name:'UpdateMat', component: UpdateMaterialComponent},
{ path : 'messages', name:'MessagesComponent', component: MessagesComponent}

])

The problem is, when I'm in any child Component, and I try refresh the page with the F5 or the browser button, the page is refreshed and redirected to RegisterClient Component always, and I want to refresh the child component and stay in the same page.

Anyone can help?

Upvotes: 0

Views: 1761

Answers (1)

Swoox
Swoox

Reputation: 3740

You already working with localstorage.

Put an ID in the localstorage after a refresh your parent check on that ID and you switch to the right page.

Upvotes: 0

Related Questions