How to use same Component for routing in Angular - javascript

I am using the same component for my router, on the first click the component affected, but on the next click the component still in the first state.
Here is the script for changing the route
<a [routerLink]="['react/1']">link 1</a>
<a [routerLink]="['react/2']">link 2</a>
Here is my router module
panel-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router'
import { PanelCoursesComponent } from 'src/app/components/panel-courses/panel-courses.component';
import { PanelHomeComponent } from 'src/app/components/panel-home/panel-home.component';
import { PanelIntroComponent } from 'src/app/components/panel-intro/panel-intro.component';
const routes: Routes = [
{ path: '', component: PanelHomeComponent },
{ path: 'react', component: PanelIntroComponent },
{ path: 'react/:no', component: PanelCoursesComponent } //the target
]
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PanelRoutingModule { }
panel-course.component.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router'
#Component({
selector: 'app-panel-courses',
templateUrl: './panel-courses.component.html',
styleUrls: ['./panel-courses.component.scss']
})
export class PanelCoursesComponent implements OnInit {
url!: any
constructor(private route: ActivatedRoute, private router: Router) {
console.log('route')
}
ngOnInit(): void {
this.url = this.router.url
console.log(this.route.snapshot.params) //the test script
}
}
On the PanelCourseComponent I try to console log the params, but that's only executed one time on the first click.
Am I missing something?

You can use this.route.params.subscribe method for this case
Here is the example
ngOnInit(): void {
this.route.params.subscribe(params => {
console.log(params) // It will be executed whenever you click the link
})
}

by default pathMatch is set to 'prefix'. so paths will be matched against your current location and the first one witch "matches" will render its component. to make your paths match only "exact" match add pathMatch: 'full' for your routes
const routes: Routes = [
{ path: '', component: PanelHomeComponent, pathMatch: 'full' },
{ path: 'react', component: PanelIntroComponent, pathMatch: 'full' },
{ path: 'react/:no', component: PanelCoursesComponent } //the target
]

Related

In Angular 13 why does my route subscription stop it hits a route without a param?

I need a way to update a variable in my header component (always displayed) whenever a param changes in the URL.
My routing:
const routes: Routes = [
{
path: '',
component: DefaultLayoutComponent,
data: {
title: 'Home'
},
children: [
{
path: 'home',
component: HomeComponent
},
{
path: 'dashboard/:id',
component: DashboardComponent,
},
]
},
{path: '**', redirectTo: 'home'}
];
The dashboard component has an ID attached to it and this is what I need to track. In the event a user goes to a page without an ID (such as the home route) I want the ID to show as 0.
I have this working to where it will track the ID as long as they continue to hit routes with an ID but as soon as they navigate to home all tracking is stopped.
header.component
import { Component, Input } from '#angular/core';
import { ClassToggleService, HeaderComponent } from '#coreui/angular-pro';
import { ActivatedRoute } from '#angular/router';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-default-header',
templateUrl: './default-header.component.html',
})
export class DefaultHeaderComponent extends HeaderComponent {
private issuer: Subscription;
constructor(private classToggler: ClassToggleService,
private route: ActivatedRoute) {
super();
}
issuerID: number;
ngOnInit(): void {
this.route.children.forEach(child => {
child.params.subscribe(params => {
const id = params['id'] || 0
console.log('id ' + id)
this.issuerID = id
})
})
}
//To prevent memory leak
ngOnDestroy(): void {
if (this.issuer)
this.issuer.unsubscribe()
}
}

Problems to redirect to auth route Angular

im starting to work with Angular, and im trying to create a simple route guard, to redirect user to login page, if my service return unauthorized.
To do that i created this route schema ->
const routes: Routes = [
{
path: '',
component: LoggedComponent,
children: [
{path: '', component: HomeComponent}
],
canActivate: [RouteGuard]
},
{
path: '',
component: AuthComponent,
children: [
{path: '', redirectTo: '/login', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'signin', component: SigninComponent}
]
},
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
And this is my guard service ->
PS: Im setting a default value false.
import {Subject, Observable} from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class RouteGuard implements CanActivate {
authorized: Subject<boolean> = new Subject();
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
this.setObservable(false)
return false;
}
getObservable(): Observable<boolean> {
console.log(`starts to observe`)
return this.authorized.asObservable();
}
setObservable(newState: boolean) {
console.log(`new observable state: ${newState}`)
this.authorized.next(newState)
}
}
Ok, since the value is returning false as default, I expect the route to be automatically redirected to the AuthComponent, because Auth is the second option at my routes[]. Right?
So...
At the AuthComponent i stated to observe the authorized status:
import {RouteGuard} from '#acn-collections-ws/shared';
#Component({
selector: 'acn-collections-ws-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {
constructor(private guard: RouteGuard, router: Router) {
console.log('im here');
this.guard.getObservable().subscribe(authorized => {
})
}
ngOnInit(): void {
}
}
But AuthComponent dosent load. it seems that when the canActivate parameter returns false, it does not go to the AuthComponent, it does not load anything. When the authorized (canActivate) returns true, it runs normally. Has anyone had a similar problem and can help me?
This is how I do it when authenticating using Firebase:
export class GuardGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router){}
async canActivate() {
const user = await this.authService.isLogged();
if(user){
return true;
}
else {
this.router.navigate(['login']);
return false;
}
}
}
If the user's logged return true so it loads the requested route if not redirects to the login route and return false.
And this is the routing:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './modules/login/pages/login/login.component';
import { SignupComponent } from './modules/login/pages/signup/signup.component';
import { HeroComponent } from './shared/components/hero/hero.component';
import { NotFoundComponent } from './shared/components/not-found/not-found.component';
import { GuardGuard } from './shared/guards/guard.guard';
const routes: Routes = [
{ path: 'home', component: HeroComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'signup', component: SignupComponent },
{ path: 'login', component: LoginComponent },
{ path: 'tasks', loadChildren: ()=> import('./modules/task/task.module').then(m => m.TaskModule), canActivate: [GuardGuard] },
{ path: 'profile', loadChildren: ()=> import('./modules/user/user.module').then(m => m.UserModule), canActivate: [GuardGuard] },
{ path: '**', component: NotFoundComponent }
];

change data on route event in Angular

How to change data in one component relatively to others on route event in Angular?
For e.g. if I have three components: "nav.component", "about.component" and "service.component".
So I want to display different text in "nav.component" when I switch between about and service pages in my app.
My "app.router.ts" file:
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServiceComponent } from './service/service.component';
export const router: Routes = [
{ path: '', redirectTo: 'about', pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'service', component: ServiceComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
I don't want to display just page name text in my nav bar while switching between these pages, it would be a custom text for each component.
Also I would like to store this data/text directly in "about.component.ts" and "service.component.ts" but not in the "app.router.ts" due to maintainability and scalability.
Is it possible?
U.P.D.
This is my "app.component.html" file:
<div class="container">
<!-- Nav Bar (text changes here) -->
<app-nav></app-nav>
<!-- Pages (components which are included in app.router.ts) -->
<router-outlet></router-outlet>
</div>
For e.g. this is "about.component.ts" file:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.scss']
})
export class AboutComponent implements OnInit {
const text_for_nav_bar = "This is my new About page."; // <-- text that should be displayed in nav component for this page on router event.
constructor() { }
ngOnInit() {
}
}
Using below code you will able to subscribe router change events. You need to add this code on nav bar.
Import router and Navigation start
import { Router, ActivatedRoute, NavigationStart } from '#angular/router';
import "rxjs/add/operator/filter";
import "rxjs/add/operator/pairwise";
Add below code in constrictor.
this.router.events
.filter(event => event instanceof NavigationStart)
.pairwise()
.subscribe((value: [NavigationStart, NavigationStart]) => {
let nextUrl = value[1].url;
if (nextUrl == '/about') {
// your code here for next url
}
},
(err) => {
},
() => { });
}
});
One way would be with *ngIf (or [hidden] if you want to load all contents to the DOM at once). And to catch current route, inject Router module:
class NavComponent {
constructor(private router: Router){
}
}
and in nav.component.html:
<div *ngIf="router.url === '/some/route'">
text for this route
</div>
<div *ngIf="router.url === '/other/route'">
text for other route
</div>
Doing same in component.ts, could be:
nav.component.html:
<h1>{{yourText}}</h1>
component.ts:
ngOnInit() {
if(this.router.url == '/some/route') {
yourText = 'Text'
} elseif(this.router.url == '/other/route') {
yourText = 'Other text'
}
}
You should use router datas
export const router: Routes = [
{ path: '', redirectTo: 'about', pathMatch: 'full' },
{ path: 'about', component: AboutComponent, data: {navigationText: 'Some text'} },
{ path: 'service', component: ServiceComponent, data: {navigationText: 'Some other text'} }
];
and in app.component.html
<div class="container">
<app-nav text="outlet.activatedRouteData.navigationText"></app-nav>
<router-outlet #outlet="outlet"></router-outlet>
</div>
Of course you need to add a "#Input text: string" property in nav.component.ts

Capture redirect route with guard in Angular2

I'm having trouble capturing the original navigating route using a guard in Angular 2.
My site consists of a core module protected by an authorization guard, and a login page that's unprotected.
The core module has it's own sub routes defined in it's own app routing file, and any undefined routes are redirected to the root path.
Here's my top level routing module.
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AuthGuard } from './auth';
const routes: Routes = [
// Login module is public
{ path: 'login', loadChildren: 'app/auth/auth.module#AuthModule' },
// Core route protected by auth guard
{ path: '', loadChildren: 'app/core/core.module#CoreModule', canLoad: [AuthGuard] },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
And here is the AuthGuard class.
import { Injectable } from '#angular/core';
import { Router, CanLoad, Route } from '#angular/router';
import { AuthService } from './auth.service';
#Injectable()
export class AuthGuard implements CanLoad {
constructor(
private authService: AuthService,
private router: Router
) {}
canLoad(route: Route): boolean {
this.authService.redirectUrl = `/${route.path}`;
console.log('path:' + route.path);
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
This is a pretty straightforward login/redirect scheme, however the route.path value is always empty, regardless of what URL I navigate to. I have a hunch that it has something to do with the { path: '**', redirectTo: '' } route but I'm not sure.
I don't want to use canActivate because I only want the main module loaded if the user is actually logged in.
What I expected was that if I navigate to /foobar then route.path would be set to foobar in the AuthGuard class but it is not. It is always empty, thus I am unable to do a correct redirect after the user logs in.
Try adding the pathMatch: 'full' like this:
{path: '**', redirectTo: '', pathMatch: 'full'}
or
import {CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from "#angular/router";
import { Subscription, Observable } from "rxjs/Rx";
export class HomepageGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
console.log(`[homepage.guard.ts]-[canActivate()]`);
console.log(route);
console.log(state);
// are you allowed to continue
return true;
}
}

Angular 2 - routing inside a component

Yesterday I asked a question about an another specific thing of angular 2 routing and the answer was satisfying for me Angular 2 — navigate through web pages without reloading a component that is common for those pages . But when I got back to examining these things, I encountered a problem again. Here's the new version of the app: http://ivan-khludov.com/ . What if I want the pages of the private section to have a shared component (a counter in my example), don't reload it each time I navigate withing the section and at the same time display different components at different pages - the dashboard component at private/dashboard and the inbox component at private/inbox? Is it possible to do without reloading the counter and without storing the last value of the counter in memory? This is the entry point of the application and the root module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { BrowserModule } from '#angular/platform-browser';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { ROUTES } from './routes';
import { AppWrapper } from './components/app-wrapper';
import { PublicSection } from './components/public';
import { PrivateSection } from './components/private';
import { Counter } from './components/counter';
import { Dashboard } from './components/private/dashboard';
import { Inbox } from './components/private/inbox';
#NgModule({
imports: [
BrowserModule,
CommonModule,
HttpModule,
RouterModule.forRoot(ROUTES)
],
declarations: [
AppWrapper,
PublicSection,
PrivateSection,
Counter,
Dashboard,
Inbox
],
providers: [
],
bootstrap: [
AppWrapper
]
})
class RootModule {}
platformBrowserDynamic().bootstrapModule(RootModule);
Routing:
import { Routes } from '#angular/router';
import { AppWrapper } from '../components/app-wrapper';
import { PublicSection } from '../components/public';
import { PrivateSection } from '../components/private';
export const ROUTES: Routes = [
{
path: '',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'section-1',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'public/:page',
component: PublicSection
},
{
path: 'private',
redirectTo: '/private/dashboard',
pathMatch: 'full'
},
{
path: 'private/:page',
component: PrivateSection
}
];
The private section component:
import { Component } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'private',
template: `
<h2>Private section — {{page}}</h2>
<counter></counter>
<dashboard></dashboard>
<inbox></inbox>
`
})
export class PrivateSection {
private page: string;
private sub: any;
constructor(
private route: ActivatedRoute
) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.page = params['page'];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
The dashboard component:
import { Component } from '#angular/core';
#Component({
selector: 'dashboard',
template: `
<div>dashboard text: lorem ipsum</div>
`
})
export class Dashboard {
}
The inbox component:
import { Component } from '#angular/core';
#Component({
selector: 'inbox',
template: `
<div>inbox text: dolor sit amet</div>
`
})
export class Inbox {
}
Thanks in advance for your answers.

Categories