Angular 2 redirect from child router - angular2-routing

I have appRoutes in my Angular 2 app
const appRoutes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{
path: 'component-two', component: AppComponent2,
children: [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
]
},
];
How I can redirect from my LoginComponent to HomeComponent?

const appRoutes: Routes = [
{
path: '',
component: LoginComponent,
children: [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
]
}
];
You have to do this.

you should use redirectTo for default redirect
const appRoutes: Routes = [
{ path: '/login', component: LoginComponent },
{ path: '/home', component: LoginComponent },
{ path: '',
redirectTo: '/login',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
from Html you can redirect like
<nav>
<a routerLink="/login" routerLinkActive="active">Login</a>
<a routerLink="/home" routerLinkActive="active">Home</a>
</nav>
inject Router to your HomeComponent's constructor
constructor(
private router: Router,
private service: HeroService
) {}
Then use this.router.navigate(['/login']); in your event function
for more details refer angular guide

Related

Unknown vue router redirection

http://localhost:8080/#/ this is the local host port that i opened but when i logged in it redirects to http://localhost:8080/?#/ . Then i have to logged in again to have my router go to http://localhost:8080/?#/admin
what is the significance of the question mark
I am using firebase authentication
here is my router index
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Admin from "../views/Admin.vue";
import ManageUsers from "../views/ManageUsers.vue";
import Funds from "../views/Funds.vue";
import CompleteDetails from "../views/CompleteDetails.vue";
import UserFunds from "../views/UserFunds.vue";
import ViewPost from "../views/ViewPost.vue";
import ResetPassword from "../views/ResetPassword.vue";
import Profile from "../views/Profile.vue";
import Overview from "../views/Overview.vue";
import Users from "../views/Users.vue";
import { fb } from "../firebase.js";
import AllUsers from "../views/Allusers.vue"
//User
import User from "../views/User.vue";
import MyProfile from "../views/MyProfile.vue";
import UserDashboard from "../views/Userdashboard.vue";
import Posts from "../views/Posts.vue";
import postEdit from "../views/postEdit.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/admin",
name: "admin",
component: Admin,
meta: { requiresAuth: true },
children: [
{
path: "funds/:user",
name: "funds",
component: Funds,
},
{
path: "userfunds",
name: "userfunds",
component: UserFunds,
},
{
path: "completedetails/:user",
name: "completedetails",
component: CompleteDetails,
},
{
path: "overview",
name: "overview",
component: Overview,
},
{
path: "posts",
name: "posts",
component: Posts,
},
{
path: "postEdit/:postId",
name: "postEdit",
component: postEdit,
},
{
path: "ViewPost/:postId",
name: "ViewPost",
component: ViewPost,
},
{
path: "users",
name: "users",
component: Users,
},
{
path: "allusers",
name: "allusers",
component: AllUsers,
},
{
path: "profile/:user",
name: "profile",
component: Profile,
},
{
path: "manageusers",
name: "manageusers",
component: ManageUsers,
},
],
},
{
path: "/user",
name: "user",
component: User,
meta: { requiresAuth: true, requiresType: true },
children: [
{
path: "myprofile/:user",
name: "myprofile",
component: MyProfile,
},
{
path: "posts",
name: "postsUser",
component: Posts,
},
{
path: "ViewPost/:postId",
name: "ViewPostUser",
component: ViewPost,
},
{
path: "userfunds",
name: "userfundsUser",
component: UserFunds,
},
{
path: "userDashboard",
name: "UserDashboard",
component: UserDashboard,
},
],
},
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/resetpassword",
name: "ResetPassword",
component: ResetPassword,
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
},
];
const router = new VueRouter({
routes,
});
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some((x) => x.meta.requiresAuth);
const currentUser = fb.auth().currentUser;
if (requiresAuth && !currentUser) {
next("overview");
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});
export default router;

How to route siblings grand child in angular 2 router

My router code is as below. When I am trying to access intro page in DashboardComponent,
it loads intro component but comes back to dashboard, what am I doing wrong?
{ path: '', component: HomeComponent, //home component
children: [
{ path: 'dashboard', component: DashboardComponent } // first child
{ path: 'main', component: ClientComponent, //2nd child
children: [
{ path:'intro', component:ClientsComponent, outlet:intro',
children: [ // grand children
{ path: '', redirectTo: 'list', pathMatch: 'full' },
{ path: 'list', component: ListComponent},
]
},
]}
}
I tried with both navigate and navigateByUrl, none seems to work:
router.navigate(['../main', {outlets: {'intro': ['intro']}}], {relativeTo: this.activatedRoute})
OR
router.navigateByUrl('main/(intro:intro/list)');

Angular2 route paths not working when URL is empty

Following is how my app's 'tree' looks like:
I want my app to go to the 'home' route by default (when the path is empty). (localhost:3000/home).
But it always goes to localhost:3000/list.
app-routing.module.ts:
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'userManagement', loadChildren: 'app/userManagement/user- management.module#UserManagementModule' }]
user-management.module.ts
const routes: Routes = [
{ path: '', redirectTo: 'list', pathMatch: 'full' },
{ path: 'list', component: UserListComponent }]
However, when the redirections works fine when triggered through HTML links:
app-component.html
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" routerLink="home" routerLinkActive="active">Home</a> <!--localhost:3000/home-->
</li>
<li class="nav-item">
<a class="nav-link" routerLink="userManagement" routerLinkActive="active">Link</a> <!--localhost:3000/userManagement/list-->
</li>
</ul>
you need to separate your routes as you separate your modules.
import { Routes } from '#angular/router';
import {UserManagementRoutes} from "./userManagement/userManagement.routes";
import {HomeRoutes} from "./home/home.routes";
export const routes: Routes = [
...UserManagementRoutes,
...HomeRoutes,
{ path: '', redirectTo: 'home', pathMatch: 'full'}
];
import {Route} from '#angular/router';
import {UserManagementComponent} from "./userManagement.component";
export const UserManagementRoutes: Route[] = [
{
path: 'userManagement',
children: [
{path: '',component: UserManagementComponent}
]
}
];
import {Route} from '#angular/router';
import {HomeComponent} from "./home.component";
export const UserManagementRoutes: Route[] = [
{
path: 'home',
children: [
{path: '',component: HomeComponent}
]
}
];

How to use angular2 child routes propely?

I am working on an angular sample app. The effect I want to get is the following:
I have a login page. When you login, you see the 'home' page. Right now, the home page is a simple html protected by authguard. I want this page to have a header section and body section. This is similar to gmail where the section at the top remain the same for all actions. For eg, the ability to logout appear in the top.
I want couple of routed in this header section that will load the different components in the body section.
This is what I have and does not seem to work.
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard]
, children: [
{path: 'home', component: HomeComponent, pathMatch: 'full'},
{ path: 'compb', component: ComponentB, outlet: 'list' },
{ path: 'compa', component: ComponentA, outlet: 'list' }
]
},
//{ path: 'compb', component: ComponentB },
//{ path: 'compa', component: ComponentA },
// otherwise redirect to home
{ path: '**', redirectTo: 'home' }
];
my home.component.html
<div class="col-md-6 col-md-offset-3">
<h1>Home</h1>
<p><a [routerLink]="['/login']">Logout</a></p>
<p><a [routerLink]="['/compb']">CompB</a></p>
<p><a [routerLink]="['/compa']">CompA</a></p>
<br/><br/>
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
Here is starting of the body!
<router-outlet name="list"></router-outlet>
Here is ending of body!
</div>
</div>
</div>
compA and compB are simple html pages to display "coponentA here" and "ComponentB here"
Any guidance will be much appreciated.
After some effort, I got it to work with child routes.
In my app.routes.ts, I initially had :
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard]
, children: [
{path: 'home', component: HomeComponent, pathMatch: 'full'},
{ path: 'compb', component: ComponentB, outlet: 'list' },
{ path: 'compa', component: ComponentA, outlet: 'list' }
]
},
//{ path: 'compb', component: ComponentB },
//{ path: 'compa', component: ComponentA },
// otherwise redirect to home
{ path: '**', redirectTo: 'home' }
];
I changed it to the following:
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard], children:homeRoutes },
// { path: 'home', component: HomeComponent, canActivate: [AuthGuard]
// , children: [
// {path: 'home', component: HomeComponent, pathMatch: 'full'},
// { path: 'compb', component: ComponentB, outlet: 'list' },
// { path: 'compa', component: ComponentA, outlet: 'list' }
// ]
// },
//{ path: 'compb', component: ComponentB },
//{ path: 'compa', component: ComponentA },
// otherwise redirect to home
{ path: '**', redirectTo: 'home' }
];
I added the following to home.routes.ts
export const homeRoutes: Routes = [
{ path: 'compa', component: ComponentA },
{ path: 'compb', component: ComponentB },
];
In my home.component.html, I added the following:
<div class="col-md-6 col-md-offset-3">
<h1>Home</h1>
<p><a [routerLink]="['/login']">Logout</a></p>
<p><a [routerLink]="['compb']">CompB</a></p>
<p><a [routerLink]="['compa']">CompA</a></p>
<br/><br/><br/><br/><br/><br/>
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
Here is starting of the body!!<br/>
<router-outlet></router-outlet>
Here is ending of body!!
</div>
</div>
</div>

Angular 2 RC5 router - nested routing

Structure
app |- admin
|- users
|- userList.Component.ts
|- userDetails.Component.ts
|- admin.component.html (contains 'router-oulet')
|- admin.component.ts
|- admin.routes.ts
|- admin.module.ts
|- dogs
|- app.component.html (contains 'router-oulet')
|- app.component.ts
|- app.routes.ts
|- app.module.ts
app.routes.ts
const appRoutes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'dogs', component: DogListComponent, canActivate: [AuthGuard] },
{ path: 'dog/:id', component: DogDetailsComponent, canActivate: [AuthGuard]},
];
export const routing = RouterModule.forRoot(appRoutes);
admin.routes.ts
const adminRoutes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AdminGuard],
children: [
{ path: '', redirectTo: '/admin/users' },
{ path: 'users', component: AdminUserListComponent },
{ path: 'user/:id', component: AdminUserDetailsComponent },
]
},
];
export const adminRouting = RouterModule.forChild(adminRoutes);
admin.userList.Component.ts
this._router.navigate(['/admin/user/', id]);
trying to navigate from AdminUserList ('admin/users') to AdminUserDetails ('admin/user/someId') but with no success.
(it seems like the scroller is going further down whenever i try to navigate to the user details)
any solution ?
you need to add pathMatch: 'full' in admin routes for default redirect,
admin.routes.ts
const adminRoutes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AdminGuard],
children: [
{ path: '', redirectTo: '/admin/users', pathMatch: 'full' },
{ path: 'users', component: AdminUserListComponent },
{ path: 'user/:id', component: AdminUserDetailsComponent },
]
},
];
export const adminRouting = RouterModule.forChild(adminRoutes);
Update
To navigate back you have couple of ways,
// In the HTML
<a [routerLink]="['/admin']" >Back</a> or <a [routerLink]="['/admin/users']" >Back</a>
// Or create a back function and use in click binding in HTML
goBack = () => {
this.router.navigate(['/admin']);
or this.router.navigate(['/admin/users']);
}

Resources