Search code examples
angularangular4-router

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


I have a web service running at :8000/re/myService

Before I implemented my router I was able to make my .get calls to myService

Get call in service.ts

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

However after the folllowing router was implemented. This call gets a 404.

Error Error

I'm trying to allow the route by adding it to my routes but it doesn't seem to work

Routes in app.module.ts

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

The rest of my 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]
})

How can I add my service path to my routes so I can hit my service correctly?


Solution

  • Looking at the error, it looks like Angular is attempting to execute the call against localhost:4200 rather than localhost:8000. In your get(), while in development you'd either need to specify the full path or utilize a proxy intercept/redirect.

    If you're using @angular/cli, you can take advantage of 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 or if the server is loading the static built Angular files, it should resolve accordingly.

    You'd create a proxy.conf.json with the following contents:

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

    You'd then execute your start/serve command as follows to indicate a proxy should be used:

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

    Hopefully that helps!