如何使用 Angular 路由器注册我的 Web 服务?

How do I register my web service with an Angular Router?

我在 :8000/re/myService

有一个网络服务 运行

在我实施我的路由器之前,我能够对 myService

进行 .get 调用

接电话 service.ts

return await this.http
  .get('/re/myService')
  .toPromise()
  .then(response => response.json().data as MyObject[])
  .catch(this.handleError);

但是在实施了以下路由器之后。此调用收到 404。

错误

我试图通过将其添加到我的路线来允许该路线,但它似乎不起作用

路线在app.module.ts

const appRoutes: Routes = [
  { path: '', component: HomePageComponent },
  { path: 'details/:id', component: MyComponent1 },
  { path: 're/myService', redirectTo: '/re/myService', pathMatch:'full'},
  {path: '**', redirectTo: ''}
];

我的 ngModule 的其余部分

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    MyComponent1,
    HeaderComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AgGridModule.withComponents(
      [
        ]
    ),
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  providers: [AppService,AppDetailsService,{provide: APP_BASE_HREF, useValue : '/' }],
  bootstrap: [AppComponent]
})

如何将我的服务路径添加到我的路由中以便我可以正确地访问我的服务?

查看错误,似乎 Angular 正在尝试对 localhost:4200 而不是 localhost:8000 执行调用。在您的 get() 中,在开发过程中您需要指定完整路径或使用代理 intercept/redirect.

如果你使用@angular/cli,你可以利用Proxy to intercept calls to specific path in development mode, and redirect them to a specified target. In PRODUCTION you'd specify the either specify the remote URL of the service endpoint using something like @angular/cli Environments,或者如果服务器正在加载静态构建的Angular文件,它应该相应地解析。

您将创建一个包含以下内容的 proxy.conf.json

{
  "/re/myService": {
    "target": "http://localhost:8000",
    "secure": false
  }
}

然后您将按如下方式执行 start/serve 命令以指示应使用代理:

ng serve --proxy-config proxy.conf.json

希望对您有所帮助!