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

时间:2017-07-10 20:36:49

标签: json angular angular2-routing angular-routing

我是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来访问该URL时,我在开发控制台中看到以下内容:

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

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

我已经尝试将api文件夹放在资产下但没有区别。

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

TLDR:是否可以通过http.get()提供一个“传递”路径,该路由服务于JSON文件?

1 个答案:

答案 0 :(得分:1)

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

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