Reputation: 77
I'm converting an existing db (Wordpress) driven site to an Angular 2 front end, keeping the backend as is. I'm at the routing stage and I want to create the routes from JSON data pulled from the db.
So, I've created a service to pull the data from the db and a separate routing module to register the routes:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NavService } from './nav.service';
var navService: NavService;
const routes: Routes = navService.getRoutes();
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRouting{}
nav.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class SiteNavService{
private _navUrl = 'pathtofile/?action=ajax_site_nav';
constructor(private _http: Http){}
getNav(){
return this._http.get(this._navUrl)
.map( res => res.json())
.toPromise();
}
}
The service is registered in the app.module.ts providers array and the routing module in the imports array. I can't get nav.service to work in the routing module file.
Upvotes: 0
Views: 1615
Reputation: 166
This is now possible using Xo for Angular: https://wordpress.org/plugins/xo-for-angular/
Xo creates dynamic routes based on your WordPress content, posts, pages, etc.
The secret sauce making this possible is the use of loadChildren in the Angular Route definition to lazy load a particular module. This is necessary as otherwise Route expects a component from an import that isn't realistic.
Example of this output from the docs site API: https://angularxo.io/xo-api/routes/get
Then in the Angular App using the angular-xo module these routes are loaded and updated by calling: router.resetConfig(response.routes);
Taken from this file: https://github.com/WarriorRocker/angular-xo-node/blob/master/lib/src/services/route.service.ts
Full disclosure, I am the author of the above plugin.
More docs (work in progress): https://angularxo.io
Example theme: https://github.com/WarriorRocker/angular-xo-material
Upvotes: 0
Reputation: 1949
I've just now been working on trying to add routes dynamically to angular 2 and found that getting the current routes with
this.router.config
and then changing them and applying the changes with
this.router.resetConfig(newRoutes);
Worked pretty well I have my demo project here that might help where team members are dynamically added from json https://github.com/davidejones/angular2-routertest
Upvotes: 1