Angular 2 router - javascript

I'm building an Angular 2 test app. I'm using the new router and it seemed to be working fine this was my code:
export class Topbar {
constructor(#Inject(Router) router: Router) {
router.config([
{path: '/displays', as: 'display', component: Display}
]);
}
}
This works now as soon as I add a second route like this I get an error:
export class Topbar {
constructor(#Inject(Router) router: Router) {
router.config([
{path: '/', as: 'home', component: MyApp},
{path: '/displays', as: 'display', component: Display}
]);
}
}
This is the error:
Configuration '/' conflicts with existing route '/'
Is this a bug or am I doing something wrong here?

I guess,
Your router config goes in your App component
and '/' routes to component: Home rather than MyApp
something like this
export class MyApp {
constructor(#Inject(Router) router: Router) {
router.config([
{ path: '/', as: 'home', component: Home },
{ path: '/about', as: 'about', component: About }
]);
}
}

Related

How to pass component into router-outlet

I have an app component an its use router-outlet, and a main component (what is loaded at router-outlet)
Now I would like to place packages in that component where we can insert widgets.
App component:
<cover></cover>
<div fxFlexFill fxLayout="row" fxLayoutAlign="stretch">
<div fxFlex>
<router-outlet></router-outlet>
</div>
</div>
Main component:
<app-header></app-header>
<main-widget></main-widget> //place where I would like to load custom content
<left-widget></left-widget> //place where I would like to load custom content
<right-widget></right-widget> //place where I would like to load custom content
Main component is come from a coreModul(share module) - this is a framework we have no access to it on project level.
So I would like to put content into widgets, but have no idea how to do that.
The hard thing to me is how to pass a component into a router-outlet and show it in right place. Its possible to use ng-templates in this case?
EDIT:
App routing:
import { RouterModule, Routes } from '#angular/router';
import {
LoginComponent,
LoginGuard,
MainComponent,
} from './../_system';
import { USERS_ROUTES, UsersComponent } from './../users';
const APP_ROUTES: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', component:MainComponent, canActivate: [LoginGuard], children: [
{ path: 'users', children: USERS_ROUTES},
{ path: '', redirectTo: '/login', pathMatch: 'full'},
{ path: '**', redirectTo: '/questions'}
]}
];
export const AppRoutingModule = RouterModule.forRoot(APP_ROUTES);

Angular2 Routing with base selector as Component in index.html

I have define 2 Routes LoginComponent and DashboardComponent and their is one main component which is the base component appComponent (which i have not used)
What I want is:
First Load the LoginComponent and then I Login Successfully then I want to Load the DashboardComponent.
What I have done is:
I have make the base component to the loginComponent as a selector in index.html page and when I successfully login the the LoginComponent View not Removed and Replace to Dashboard Page.
Here is my Code:
Routes:
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/login',pathMatch:'full' },
{ path: '**', component: NotFound404Component }
];
Used this for login function:
this.router.navigate(['/dashboard']);
Any help would appriciated.

Angular2 when I refresh the page, not the page loads in router params

My application loads normally in all routers but when I use
router with params the application can not loaded.
example: localhost:3000/usersid/:id
the router code is :
const appRoutes: Routes = [
{ path: 'user', component: UserComponent },
{ path: 'info', component: InfoComponent },
{ path: 'users', component: UsersComponent },
{ path: 'usersid/:id', component: UsersIdComponent },
{ path: '', component: MainComponent },
{ path: '**', component: MainComponent }
];
and the component of the params router
import{Component} from '#angular/core'
import { ActivatedRoute } from '#angular/router';
import * as Datastore from 'nedb';
#Component({
moduleId : module.id ,
templateUrl : 'userid.component.html' ,
styles : [`
.SamRouter {
overflow-y: auto;
}
`]
})
export class UsersIdComponent {
id: any;
private sub: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sub = this.route.params.subscribe( params => {
// this.id = +params['id']; // (+) converts string 'id' to a number
this.id = params['id'] || 0 ;
// In a real app: dispatch action to load the details here.
});
console.log( this.id )
}
ngOnDestroy() {
// this.sub.unsubscribe();
}
}
Error Message:
http://localhost:3000/users/node_modules/bootstrap/dist/js/b‌​ootstrap.min.js
Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:3000/users/styles.css Failed to load
resource: the server responded with a status of 404 (Not Found)
It depends what server you are using.
you need to configure your server to go to index.html whenever the route is not exists.
while you press F5 the server search for a file that isn't exists, the server should return index.html and only then the angular router will do the rest.
Change this:
const appRoutes: Routes = [
{ path: 'user', component: UserComponent },
{ path: 'info', component: InfoComponent },
{ path: 'users', component: UsersComponent },
{ path: 'usersid/:id', component: UsersIdComponent },
{ path: '', component: MainComponent },
{ path: '**', component: MainComponent }
];
To this: (pay attention to the fourth element in Routes array)
const appRoutes: Routes = [
{ path: 'user', component: UserComponent },
{ path: 'info', component: InfoComponent },
{ path: 'users', component: UsersComponent },
{ path: 'users/:id', component: UsersIdComponent },
{ path: '', component: MainComponent },
{ path: '**', component: MainComponent }
];

Routing submenu elements Angular 2

I have a question regarding routing submenu elements in Angular 2.
The directory of my project looks like:
-app
---login
---registration
---mainApp (this is the main body of the app, with a static content as menu, with few links)
-----subMenu1 (link to some content)
-------(some files here)
-----subMenu2 (link to some content)
-------(some files here)
-----subMenu3 (link to some content)
-------(some files here)
---app.component.ts
---app.component.html
---app.module.ts
---app.routing
---index.ts
How does it works? First view is the login and there you have two possibilities, to enter the mainApp or enter registration form. It works fine. But now I need to handle the routing between the mainApp and sub items from this mainApp. The mainApp content is just a sidemenu, which doesn't disappear. It is always on screen, only content from sidemenu elements is changing.
What is my problem:
Do I need to provide another routing file to handle the routing between the mainApp static menu elements and the dynamic content? Or am I able to do it just from this file which handles routing between the app and login, registration and mainApp?
And if I have to make another routing file, how would it look like?
My actual routing file looks like:
import { Routes, RouterModule } from '#angular/router';
import { MainAppComponent} from './mainApp/index';
import { LoginComponent } from './login/index';
import { RegistrationComponent } from './registration/index';
const appRoutes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'mainApp', component: MainAppComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);
Let's say that I provide another routing file, would it look like this?
import { Routes, RouterModule } from '#angular/router';
import { subMenu1Component } from './subMenu1/index';
import { subMenu2Component } from './subMenu2/index';
import { subMenu3Component } from './subMenu3/index';
const appRoutes: Routes = [
{ path: '', component: mainAppComponent},
{ path: 'subMenu1', component: subMenu1Component },
{ path: 'subMenu2', component: subMenu2Component },
{ path: 'subMenu3', component: subMenu3Component },
{ path: '**', redirectTo: '' }
];
export const routing = RouterModule.forRoot(appRoutes);
I like to split my routes off into layouts. So typically I do a secure layout and a public layout. This way I can control the authentication of the website and protect data that was meant to be secure.
In order to do this I keep a file structure as shown below,
/app.module.ts
/app.routing.ts
/layouts/secure.component.ts
/layouts/secure.component.html
/layouts/public.component.ts
/layouts/public.component.html
/secure/profile.component.ts
/secure/profile.component.html
/secure/secure.routes.ts
/public/home.component.ts
/public/home.component.html
/public/public.routes.ts
Explanation
Initially we need to register all of our components and setup the routes.
Register Components
/app.module.ts
//Layouts
import { PublicComponent } from './layouts/public.component';
import { SecureComponent } from './layouts/secure.component';
import { HomeComponent } from './public/home.component';
import { ProfileComponent } from './secure/profile.component';
#NgModule({
declarations: [
AppComponent,
PublicComponent,
SecureComponent,
HomeComponent,
ProfileComponent
],
providers: [
Guard,
Auth
]
Take special notice to the Auth under providers. This is what will help us secure the secure layout.
Next we will setup the routes.
app.routing.ts
const APP_ROUTES: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full', },
{ path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
{ path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
];
As you can see the [Guard] is setup using the Auth provider and is a service I use to secure the secure layouts. Now that each of these routes actually have children routes we can set those routes up to control the actual navigation of our app.
It is important to understand. These routes will direct traffic to the correct layout. Then depending on the route the child routes take over. Which in your case would be your sub components.
/secure/secure.routes.ts
import { ProfileComponent } from './profile.component';
export const SECURE_ROUTES: Routes = [
{ path: '', redirectTo: 'profile', pathMatch: 'full' },
{ path: 'profile', component: ProfileComponent },
];
Remember to import your component to the routes file so it knows which class to call when the route is enabled.
For extra credit I will go ahead and throw in a service to provide auth. This will show you how to protect your routes.
guard.service.ts
import { Injectable } from '#angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { Auth } from './auth.service';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class Guard implements CanActivate {
constructor(protected router: Router, protected auth: Auth ) {}
canActivate() {
if (localStorage.getItem('access_token')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page
this.router.navigate(['/home']);
return false;
}
}
By storing a token in the local storage we can check to see if it exist and authenticate the user. Once they meet the criteria they gain access to the secure routes.
Let me know if you have anymore questions.

Using children states in Angular 2 router throws error

Heres my router config:
import { RouterConfig } from '#angular/router';
...
export const AppRoutes : RouterConfig = [
{
path: '',
redirectTo: 'myview',
pathMatch: 'full'
},
{
path: 'myview',
component: ViewComponent,
children: [{
path: 'hello',
component: HelloComponent
}]
},
];
When I try to load the page I get the following error:
EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: ''
However, when I make the child route a sibling, like this:
export const AppRoutes : RouterConfig = [
{
path: '',
redirectTo: 'myview',
pathMatch: 'full'
},
{
path: 'myview',
component: ViewComponent
},
{
path: 'hello',
component: HelloComponent
}
];
I am able to load the page fine without any errors. What am I doing wrong?
Because the way you have designed it is on initial load it is landing on ViewComponent component but ViewComponent has child so have to redirect to inner component.
You need to add one more route to children routes which will redirect '' to hello component.
export const AppRoutes: RouterConfig = [
{ path: '', redirectTo: 'myview', pathMatch: 'full'},
{ path: 'myview', component: ViewComponent,
children: [
{ path: '', pathMatch: 'full', redirectTo: 'hello' }, //added redirection to hello
{ path: 'hello', component: HelloComponent }
]
}
];
Note: Make sure you have <router-outlet></router-outlet> in myview component HTML so that child route view can be shown
correctly.
You are not using any route for '' in your RouterConfig.
As after redirect the new path will be https://yourdomain/myview/. And for this you have only created https://yourdomain/myview/hello route in routeCofig
I have created an app in angular 2. You can check the source here on Github.
Just add following line to your children path array:
{path: '', component: HelloComponent }
Check hero.routes.ts and dragon.routes.ts files they will help you understand routing more clearly. Hope it will help. Thank you.

Categories

Resources