Angular 4在路由模块中使用服务 [英] Angular 4 using a service in routing module
问题描述
我正在尝试使用Laravel REST API创建一个简单的CMS系统.对于前端,我使用Angular 4框架&角度CLI.现在,我正在尝试生成动态路由(通过使用服务从API获取页面并为每个页面生成路由).我通过本地数据模拟进行了尝试,并使它像这样工作.
I'm trying to make a simple CMS system using a Laravel REST API. For the front-end i'm using the Angular 4 framework & angular CLI. Now i'm trying to generate dynamic routes (fetching pages from the API by using a service & generating routes for each of these pages). I tried this with a local data simulation and got this working like this.
Routing.module.ts
let cmsService: CmsService = new CmsService();
const pages = cmsService.getPageNames();
const routes: Routes = [
{ path: '', component: OverviewComponent },
{ path: 'login', component: LoginComponent}
];
for (let i = 0; i < pages.length; i++) {
routes.push(
{ path: pages[i].toString(), component: PageEditComponent}
);
}
我知道这可能不是最好的做事方法,但它确实有效.现在,我必须注入HTTP,整个过程都失败了,因为以下项不再起作用,因为它期望注入HTTP.
I know this probably isn't the best way of doing thing but it worked. Now i have to inject HTTP and the whole thing came down because the following isn't working anymore since it's expecting to get http injected.
let cmsService: CmsService = new CmsService();
我也许可以通过使http变量以某种方式传递它,但是感觉有点脏.所以我开始怀疑是否没有更简单的方法可以做到这一点.例如,按预期方式注入服务,而不是创建新服务.并为以这种方式检索的页面创建路由.
I could probably just pass it by making the http variable in someway but it feels kinda dirty. So i started wondering if there wasn't an easier way of doing this. For example injecting the service like you're supposed to instead of creating a new service. And create routes for the pages retrieved in this way.
提前谢谢!
推荐答案
要在任何组件或模块中使用服务,必须将其导入提供商.在提供程序部分的app.module.ts中.
To use a service in any component or module you have to import it in your providers. In the app.module.ts in the section of providers.
providers: [YourService]
别忘了在app.module.ts顶部导入服务
Don't forget to import the service at the top of the app.module.ts
import { YourService } from './yourPath';
这篇关于Angular 4在路由模块中使用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!