Harinder
Harinder

Reputation: 343

angular2 serving local JSON file via http.get while having custom routing rules

I am very new to Angular and running into an issue while trying to get a local .json file via http.get. This is due to my routing rules but I'm not sure how to fix it.

Directory Structure:

api
    mockAppointments.json
app
    app.component.*
scheduler
    scheduler.component.*

scheduler.component.ts where http.get() call is made:

getAppointments() {
return this.http
.get('api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}

Routing rules:

const appRoutes: Routes = [
  {
    path: 'scheduler',
    component: SchedulerComponent
  },
  {
    path: '',
    redirectTo: '/scheduler',
    pathMatch: 'full'
  }
];

As I browse to http://localhost:4200/scheduler, the page loads as expected but dev console has the error:

GET http://localhost:4200/api/mockAppointments.json 404 (Not Found)

When I try to get to that URL by typing it in the browser, I see the following in dev console:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL 
Segment: 'api/mockAppointments.json'

So it's clear that the issue is with routing. For now I need all URLs redirected to /scheduler (which is happening). When I make a http.get('api/mockAppointments.json') call, it should just serve that as is, almost like a pass through. Everything I have looked at, I would need a component to go along with any routing rule. That is fine, but there wouldn't be a template associated with it.

I have tried putting the api folder under assets but it made no difference.

Eventually the api call would be external to the app so this wouldn't be an issue but how do I get it working during development?

TLDR: Is it possible to have a 'pass through' route which serves a JSON file as is via http.get() ?

Upvotes: 1

Views: 1979

Answers (1)

CharanRoot
CharanRoot

Reputation: 6325

copy your api folder into assets folder. Angular can only access files from assets folder.

getAppointments() {
return this.http
.get('assets/api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}

Upvotes: 1

Related Questions