Search code examples
javascriptangularangular-routingangular-router

Angular load url when using a router


Im using Angular 7 + router. For example, my home page is localhost:4200, one of my router's url is localhost:4200/route and I have an API end point at localhost:4200/api/foo.

I'm trying to let the browser load the api end point from both locations. If I put an anchor with href pointing to the API end point, both anchor link works perfectly. However, I need to do it programmatically and I have tried all of the following methods

window.open("localhost:4200/api/foo","_self")
window.location.replace('localhost:4200/api/foo');
window.location.href = 'localhost:4200/api/foo';

They all works on the home page but if I'm in the router page, doing so will get me to the home page.

Any help is greatly appreciated!

To be specific, I have a spring boot server with url patterns like /api/*. All other urls are handled by angular. I want the browser to load localhost:4200/api/foo, which is directly handled by a get request defined in the server

Demo:

My nav bar is a component and it stays the same regardless of the router. The code behind that button click is below. Note that the first time I click it under some Angular routed url, it loads the home page, not google.com

onLogIn() {
    window.open('https://www.google.com',"_self");
}

Routing.ts file

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { IndexComponent } from "./index/index.component";
import { MicroserviceComponent } from "./microservice/microservice.component";

const routes: Routes = [
    { path: '', component: IndexComponent},
    { path: 'microservice/:id', component: MicroserviceComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Solution

  • add pathMatch to your empty route, it's missing tht's why you're redirected to the home component

    const routes: Routes = [
     { path: '', component: IndexComponent, pathMatch:'full'},
     { path: 'microservice/:id', component: MicroserviceComponent}
    ];