Dai
Dai

Reputation: 155503

Angular 5 router.navigate takes me away from the Angular application

In my app.routing.ts file I set these routes up:

const appRoutes: Routes = [
    { path: 'home'  , component: HomeComponent },
    { path: 'misc'  , component: MiscComponent },
    { path: 'help'  , component: HelpComponent },
    { path: 'auth'  , component: AuthComponent },

    { path: ''      , redirectTo: '/home', pathMatch: 'full' },
    { path: '**'    , component: NotFoundComponent }
];

Consequently, when a user accesses http://localhost/cool the Angular application loads and then pushes a history-state to become http://localhost/cool/home (so the address bar changes but the browser doesn't do a full-page-reload of the new location). So far, so good.

There's a log-out button in my page (in HTML controlled by AppComponent) that when clicked does this:

class AppComponent {

    logOutClicked( event: Event): void {

        this.clientTokenService.clearSavedToken();

        this.router.navigate( ['auth'] );
    }
}

...but when this happens the browser does a full page refresh for either http://localhost or http://localhost/auth (I forget what caused it to do that, I think it was when I did router.navigate( ['/auth'] ) - I don't have access to the Angular application right now to check).

I'm surprised there isn't an explicit option or function on Angular's router to force it to do an "internal redirect" without causing a full page reload - or is there and I'm just missing something?

Upvotes: 1

Views: 796

Answers (2)

oeste
oeste

Reputation: 1539

Use a router link instead of an href. This will route with no reload

<a routerLinkActive="active" [routerLink]="['/cool']">Cool Page</a>

Upvotes: 2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Change your "a" tag to a div or a span. When you have an 'a" tag with no href attribute and no routerLink attribute, it is still a link, with a defualt value which I think is "/".

Upvotes: 0

Related Questions