使用路由器时的角度加载URL

问题描述 投票:0回答:1

我正在使用Angular 7 +路由器。例如,我的主页是localhost:4200,我的路由器的一个网址是localhost:4200/route,我在localhost:4200/api/foo有一个API终点。

我试图让浏览器从两个位置加载api端点。如果我使用href指向API端点的锚点,两个锚点链接都可以正常工作。但是,我需要以编程方式执行此操作,并尝试了以下所有方法

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

它们都在主页上工作但如果我在路由器页面中,这样做会让我进入主页。

任何帮助是极大的赞赏!

具体来说,我有一个带有/ api / *等url模式的spring boot服务器。所有其他网址都由角度处理。我希望浏览器加载localhost:4200/api/foo,它直接由服务器中定义的get请求处理

演示:

我的导航栏是一个组件,无论路由器如何,它都保持不变。该按钮单击背后的代码如下所示。请注意,我第一次在某个Angular路由网址下单击它时,会加载主页,而不是google.com

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

Routing.ts文件

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 { }
javascript angular angular-routing angular-router
1个回答
1
投票

将pathMatch添加到您的空路径,它会丢失,这就是您重定向到主组件的原因

const routes: Routes = [
 { path: '', component: IndexComponent, pathMatch:'full'},
 { path: 'microservice/:id', component: MicroserviceComponent}
];
© www.soinside.com 2019 - 2024. All rights reserved.