问题
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}
);
}
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();
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.
Thanks in advance!
回答1:
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]
Don't forget to import the service at the top of the app.module.ts
import { YourService } from './yourPath';
来源:https://stackoverflow.com/questions/47286034/angular-4-using-a-service-in-routing-module