angular2 通过 http.get 服务本地 JSON 文件,同时具有自定义路由规则

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

我是 Angular 的新手,运行 在尝试通过 http.get 获取本地 .json 文件时遇到了一个问题。这是由于我的路由规则造成的,但我不确定如何解决它。

目录结构:

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

scheduler.component.ts 调用 http.get() 的地方:

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

路由规则:

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

当我浏览到 http://localhost:4200/scheduler 时,页面按预期加载,但开发控制台出现错误:

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

当我尝试通过在浏览器中键入它来访问 URL 时,我在开发控制台中看到以下内容:

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

很明显问题出在路由上。现在我需要将所有 URL 重定向到 /scheduler (这正在发生)。当我进行 http.get('api/mockAppointments.json') 调用时,它应该按原样提供服务,几乎就像传递一样。我所看到的一切,我都需要一个组件来配合任何路由规则。这很好,但不会有与之关联的模板。

我试过将 api 文件夹放在 assets 下,但没用。

最终 api 调用将在应用程序外部进行,因此这不会成为问题,但我如何在开发过程中使其正常工作?

TLDR:是否有可能通过 http.get() 有一个 'pass through' 路由服务于 JSON 文件?

将您的 api 文件夹复制到资产文件夹中。 Angular 只能访问 assets 文件夹中的文件。

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