Angular2 Routes from json

85 views
Skip to first unread message

Роман Р.

unread,
Mar 17, 2017, 2:40:22 PM3/17/17
to Angular and AngularJS discussion
Hi All!

Is it possible to load Angular2 Routes from remote json file?

[
 
{
   
"path": "users",
   
"component": "views.UserTreeView"    
 
}  
]






@Injectable()
export class NavigationService {

    constructor
(private http: Http) {
   
}

    loadRoutes
(): Observable<Routes> {
       
debugger;
       
return this.http.get(navigationUrl)
           
.map((r: Response) => r.json())
           
.map((items: Array<any>) => {
               

               
return items.map(i => <any>{ path: i.path, component: i.component })

                           
           
});
   
}    
}

And load in app.component

ngOnInit() {

       
// Маршруты
       
this.navigationService
           
.loadRoutes()
           
.subscribe(routes => {
               
this.router.resetConfig(routes);
               
               
this.router.navigate(['users']);      
           
});      
         
   
}

Such approach always gets error- No component factory found for views.UserTreeView


Thanks.

Sander Elias

unread,
Mar 18, 2017, 4:58:22 AM3/18/17
to Angular and AngularJS discussion
Hi Роман,

You have to make sure the component is (lazy) loaded before you can add it to the route.

Regards
Sander

Tyler Garland

unread,
Apr 13, 2017, 7:02:05 PM4/13/17
to Angular and AngularJS discussion
Can you clarify, Sander?

Sander Elias

unread,
Apr 14, 2017, 2:21:00 AM4/14/17
to Angular and AngularJS discussion
Hi Tyler,

You can't add components to your router that are unknown to angular. So, if you want to add routes dynamically, you have to make sure, those components are loaded before you create the route.
One can use lazy loading (outside of the router) to load them, before creating the routes. 

As an alternative, you can add lazy loading routes to the router. But then you are pulling in ngModules instead of components. 
While I'm thinking on this, I'm not sure this would fly with the AOT compiler, too bad I lack the time to try that right now ;)

Regards
Sander

Tyler Garland

unread,
Apr 14, 2017, 10:23:03 AM4/14/17
to Angular and AngularJS discussion
Thanks, Sander. I have a small hack in place where I just put every component I need in the entryComponents of the app component.

--
You received this message because you are subscribed to a topic in the Google Groups "Angular and AngularJS discussion" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/L_S3c5CD6aY/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages