Angular 6 Dynamic Routing Table From Database - javascript

I want to define the routing table in app.routing.ts from the database. The data for the routing file will be retrieved from the table in the database on the initialization of the project.
I have tried the same by making an HTTP Get call from app.component.ts and adding the routes from the same file into routes configure.
It doesn't give the error when I add the route after making the database call and adding the same. When I route the same, It gives the me an error that no routes are available.
Please help me out the same. Any kind of help is appreciated
I have tried to develop the prototype for the same.
app.component.ts
import { Component } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
import { Routes } from '#angular/router';
import { Router } from '#angular/router';
import { AppModule } from './app.module';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
routes: Routes = [];
data: any;
loaded: boolean = false;
constructor(private http: HttpClient, private router: Router) {
this.getJSON().subscribe(data => {
//routes.push(data);
if (!this.loaded) {
let routerConfig = this.router.config;
//routerConfig.unshift(data[0]);
// routerConfig[0]._loadedConfig.routes[0].children.unshift({
// path: `lazy`,
// loadChildren: 'app/lazy.module#LazyModule'
// });
// console.log('/lazy route (Portal child) added',
routerConfig);
//this.router.resetConfig(routerConfig);
let compName = data[0].component;
let comp: any =
(<any>AppModule).__annotations__[0].declarations.find(comp =>
{
return comp.name === compName;
});
routerConfig.unshift({path: 'login', component:
mapping[comp]})
this.router.resetConfig(routerConfig);
this.loaded = true;
}
});
}
public getJSON(): Observable<any> {
return this.http.get("https://api.myjson.com/bins/1g16wr");
}
}
//app.routing.ts
import { RouterModule, Routes } from '#angular/router';
import { LoginComponent } from "./login/login.component";
import { AddUserComponent } from "./add-user/add-user.component";
import { ListUserComponent } from "./list-user/list-user.component";
import { EditUserComponent } from "./edit-user/edit-user.component";
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
const routes: Routes = [];
// function f(){
// console.log(this.http.get("https://api.myjson.com/bins/mfh63"));
// }
// f();
// const routes: Routes = [
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// export class TestComponent implements OnInit {
// constructor(private http: HttpClient) {
// console.log('second');
// this.getJSON().subscribe(data => {
// let testData = data;
// routes.push(testData);
// console.log(routes);
// });
// }
// ngOnInit() {
// console.log('first');
// }
// public getJSON(): Observable<any> {
// return this.http.get("https://api.myjson.com/bins/mfh63");
// }
// }
export const routing = RouterModule.forRoot(routes);
app.component.html
<router-outlet></router-outlet>
app.module.ts
import { RouterModule, Routes } from '#angular/router';
import { LoginComponent } from "./login/login.component";
import { AddUserComponent } from "./add-user/add-user.component";
import { ListUserComponent } from "./list-user/list-user.component";
import { EditUserComponent } from "./edit-user/edit-user.component";
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs';
const routes: Routes = [];
// function f(){
// console.log(this.http.get("https://api.myjson.com/bins/mfh63"));
// }
// f();
// const routes: Routes = [
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// { path: 'login', component: LoginComponent },
// { path: 'add-user', component: AddUserComponent },
// { path: 'list-user', component: ListUserComponent },
// { path: 'edit-user', component: EditUserComponent },
// { path: '*', component: LoginComponent }
// ];
// export class TestComponent implements OnInit {
// constructor(private http: HttpClient) {
// console.log('second');
// this.getJSON().subscribe(data => {
// let testData = data;
// routes.push(testData);
// console.log(routes);
// });
// }
// ngOnInit() {
// console.log('first');
// }
// public getJSON(): Observable<any> {
// return this.http.get("https://api.myjson.com/bins/mfh63");
// }
// }
export const routing = RouterModule.forRoot(routes);
it shows that the specific route is not found. If anything specific is needed, please reply I will upload you the project.

Related

route navigation is not working in angular 9

I am working on a login and home component in my angular app.
Login service is validating the username and password of the user.
After successful login, it should redirect user to the home page.
But router redirect is not working properly.
login component
import { Router } from '#angular/router';
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { User } from 'src/app/shared/models/user';
import { AuthService } from '../services/auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
userName: FormControl;
password: FormControl;
loginFormGroup: FormGroup;
loginError: boolean;
errorMessage: string;
messageString: string;
constructor(private router: Router, private authService: AuthService) { }
ngOnInit() {
this.userName = new FormControl("", [Validators.required]);
this.password = new FormControl("", [Validators.required]);
this.loginFormGroup = new FormGroup({
userName: this.userName,
password: this.password
});
}
login() {
this.loginError = false;
if (this.loginFormGroup.valid) {
let user: User = new User();
user.userId = this.userName.value;
user.password = this.password.value;
this.authService.login(user)
.subscribe(res =>
{
console.log(res)
this.router.navigate(["home"])
console.log("res")
},
error =>
{
console.log(error)
});
}
}
}
and login service
import { Injectable } from "#angular/core";
import { Router } from "#angular/router";
import { Observable } from "rxjs";
import { share } from "rxjs/operators";
import { environment} from 'src/environments/environment';
import { HttpClient, HttpParams, HttpHeaders} from "#angular/common/http";
import { User } from 'src/app/shared/models/user';
#Injectable({ providedIn: "root" })
export class AuthService {
user: User;
resp=401;
get userDetail(): User {
return this.user;
}
constructor(
private router: Router,
private http: HttpClient
) {
}
login(user: User): Observable<any> {
var formData = new FormData();
formData.append("userId", user.userId);
formData.append("password", user.password);
return this.http.get<any>(url+"Validate_Login_User",{
headers: new HttpHeaders(),
params: new HttpParams().set("User_Id","user.userId")
})
}
}
routes
import { NgModule } from "#angular/core";
import { Routes, RouterModule } from "#angular/router";
import { AuthGuard } from "./authentication/services/auth.guard";
import { LoginComponent } from "./authentication/login/login.component";
import { LayoutComponent } from "./shared/components/layout/layout.component";
import { PageNotFoundComponent } from "./shared/components/page.not.found.component";
import { MenuComponent } from './menu/menu.component';
const routes: Routes = [
{ path: "login", component: LoginComponent },
{
path: "home",
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{
//childroutes
},
{
//childroutes
},
],
},
{ path: "**", component: PageNotFoundComponent },
{ path: "Menu", component: MenuComponent}
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: "ignore",
useHash: true,
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
console log in login component
even though the console is printing success, route navigate is not happening and its still in login page
replace your code with the following piece of code, that should work.
this.loginError = false;
if (this.loginFormGroup.valid) {
let user: User = new User();
user.userId = this.userName.value;
user.password = this.password.value;
this.authService.login(user)
.subscribe(res =>
{
console.log(res)
this.router.navigate(["/home"])
console.log("res")
},
error =>
{
console.log(error)
});
}
}
Edited:
Please replace your ngModule with the below code:
#NgModule({
imports: [
RouterModule.forRoot(routes, {
useHash: true,
}),
],
exports: [RouterModule],
})
Try this.
this.router.navigateByUrl('/home');

Expected spy navigate to have been called

I have created a route after user logged-in in my angular app (Angular 8). now am trying to write a test case. But its giving below error.
route (/profile) page was not able to call.
Expected spy navigate to have been called with:
[ [ '/profile' ] ]
but it was never called.
login.component.js
import { Component, OnInit } from '#angular/core';
import { UserService } from '../../services/user.service';
import { User } from '../../models/user';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
user: User = new User();
errorMessage: string;
constructor(private userService: UserService, private router: Router){ }
ngOnInit(): void {
if(this.userService.currentUserValue){
this.router.navigate(['/home']);
return;
}
}
login() {
this.userService.login(this.user).subscribe(data => {
this.router.navigate(['/profile']);
}, err => {
this.errorMessage = "Username or password is incorrect.";
});
}
}
login.component.spec.ts
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { LoginComponent } from './login.component';
import { UserService } from 'src/app/services/user.service';
import { Router } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { ExpectedConditions } from 'protractor';
import { DebugElement } from '#angular/core';
import { RouterTestingModule } from '#angular/router/testing';
import { HomeComponent } from '../home/home.component';
import { ProfileComponent } from '../profile/profile.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let debugElement: DebugElement;
let location, router: Router;
let mockRouter;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule, FormsModule ],
declarations: [ LoginComponent, ProfileComponent ],
providers: [UserService]
})
.compileComponents();
}));
beforeEach(() => {
mockRouter = { navigate: jasmine.createSpy('navigate') };
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([
{ path: 'profile', component: ProfileComponent }
])],
declarations: [LoginComponent, ProfileComponent],
providers: [
{ provide: Router, useValue: mockRouter},
]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
});
it('should go profile ', async(() => {
fixture.detectChanges();
component.login();
expect(mockRouter.navigate).toHaveBeenCalledWith(['/profile']);
}));
});
Why are you configuringTestingModule twice?
You should mock userService.
Try:
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { LoginComponent } from './login.component';
import { UserService } from 'src/app/services/user.service';
import { Router } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { ExpectedConditions } from 'protractor';
import { DebugElement } from '#angular/core';
import { RouterTestingModule } from '#angular/router/testing';
import { HomeComponent } from '../home/home.component';
import { ProfileComponent } from '../profile/profile.component';
import { of } from 'rxjs'; // import of from rxjs
import { throwError } from 'rxjs'; // import throwError
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let debugElement: DebugElement;
let mockUserService = jasmine.createSpyObj('userService', ['login']);
mockUserService.currentUserValue = /* mock currentUserValue to what it should be */
let router: Router;
beforeEach(async(() => {
// I don't think you need HttpClientTestingModule or maybe FormsModule
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule, FormsModule, RouterTestingModule.withRoutes([
{ path: 'profile', component: ProfileComponent }
])],
declarations: [LoginComponent, ProfileComponent],
providers: [{ provide: UserService, useValue: mockUserService }]
})
.compileComponents();
}));
beforeEach(() => {
router = TestBed.get(Router); // remove the let here !!!!
spyOn(router, 'navigate'); // spy on router navigate
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
});
it('should go profile ', async(() => {
fixture.detectChanges();
mockUserService.login.and.returnValue(of({})); // mock login method on userService when it is called
component.login();
expect(router.navigate).toHaveBeenCalledWith(['/profile']);
}));
it('should set error message on error ', async(() => {
fixture.detectChanges();
mockUserService.login.and.returnValue(throwError('Error')); // mock login method on userService when it is called
component.login();
expect(component.errorMessage).toBe('Username or password is incorrect.');
}));
});

change navigation on router events fired

i want to change destination route after navigation start.
i've creating an app using angular i want if user click browser back button i change user navigation to home page. in my app.component i check navigation but router navigation doesn't fire:
constructor(router: Router) {
router.events.subscribe((val: NavigationStart) => {
if (val.navigationTrigger === 'popstate') {
router.navigate['home'];
}
});
}
is it a way to change destination route after router events fired?
Update:
my AppRoutingModule contain :
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: 'account', loadChildren: () => import('./account/account.module').then(m => m.AccountModule) },
{ path: '', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
{ path: 'notification', loadChildren:() => import('./notification/notification.module').then(x=> x.NotificationModule) }
];
....
export class AppRoutingModule { }
and my For Example NotificationRoutingModule :
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { NotificationComponent } from './notification.component';
import { ListComponent } from './list/list.component';
import { DetailComponent } from './detail/detail.component';
const routes: Routes = [
{path: '' ,component: NotificationComponent,children: [
{path: '', redirectTo: 'list', pathMatch: 'full'},
{path: 'list', component: ListComponent},
{path: 'detail/:id', component: DetailComponent}
]}
];
....
export class NotificationRoutingModule { }
and my HomeRoutindModule is contain :
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { HomeComponent } from './home.component';
const routes: Routes = [
{path: '' , component : HomeComponent},
{path: 'home' , component : HomeComponent},
];
....
export class HomeRoutingModule { }
i want if user went to navigation ('notification') after he press browser navigation i change next navigation whatever it was ,navigation change to something like 'home'.
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
constructor(router: Router) {
router.events.subscribe((val: NavigationStart) => {
if (val.navigationTrigger === 'popstate') {
// if val.url equal '/notification/list'
router.navigate['\home'];
// i tried it but navigation does't changed
}
});
}
}
router navigation method give an array as commands and an object as extras object (NavigationExtras interface).and NavigationExtras interface has a property as replaceUrl
for replacing the current state whatever it was.then i changed my code to:
constructor(router: Router) {
router.events.subscribe((val: NavigationStart) => {
if (val.navigationTrigger === 'popstate') {
// here changed
router.navigate(['home'], {replaceUrl:true});
}
});
}
Place Html component.html as
<input type="button" name="" value="Back" (click)="Home()" class="btn btn secondary"/>
Place component.ts as
import { Router } from "#angular/router";
constructor(private router: Router){}
component.ts Method as
Home() {
this.router.navigateByUrl('');
}
import { HostListener } from '#angular/core';
and then listening for popstate on the window object
#HostListener('window:popstate', ['$event'])
onPopState(event) {
console.log('Back button pressed');
// Here write navigation route
}
router.navigate(['/home'])
I replicated your code locally and made a change I hope this works.
yourFunction {
this.router.events.subscribe((ev) => {
if (ev instanceof NavigationStart && ev.navigationTrigger === 'popstate') {
this.router.navigate(["home"]);
}
})
}
constructor(...) {
this.yourFunction()
}

Angular 6 + Routes Resolver = 404 page in production

I am new to Angular Community coming from rails ; I am working on a site where I can post case studies of my clients website. So far I am loving angular but I am running into an issue that worries me a bit. The issue that I cant seem to use hyperlinks to reference any of the projects. For example if you click on this the application will return a 404 status but if you start from the root page everything will run no problem.
Solutions I have tried
Adding a resolver to the route to fetch the data before loading the
page; it works but still no hyperlink.
Can anyone help me figure out what I am missing or doing wrong;
Below is my code; Any help would be appreciated
Project.service.ts
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable, of } from 'rxjs';
import { map, } from 'rxjs/operators';
import { Injectable } from '#angular/core';
import { Project } from '../../models/project';
import { HttpClient } from '#angular/common/http';
import { Post } from '../post';
#Injectable()
export class ProjectService {
ProjectListRef: Observable<any[]>;
featuredProjectList: Observable<any[]>;
posts: Array<Post>;
constructor( private database: AngularFirestore, private http: HttpClient) {
// Link For All Projects Page
const allProjectsListLink = this.database.collection<Project>('projects', ref => ref.orderBy('company_name'));
// Link For Featured Project Page
const featuredProjectsListLink = this.database.collection<Project>('projects', ref => ref.limit(5));
this.ProjectListRef = allProjectsListLink.snapshotChanges()
// using map pipe
.pipe(map( actions => {
return actions.map(a => {
// Get Document Data
const data = a.payload.doc.data() as Project;
// Get Document Id
const id = a.payload.doc.id;
return {id, ...data};
});
}));
this.featuredProjectList = featuredProjectsListLink.snapshotChanges()
// using map pipe
.pipe(map( actions => {
return actions.map(a => {
// Get Document Data
const data = a.payload.doc.data() as Project;
// Get Document Id
const id = a.payload.doc.id;
return {id, ...data};
});
}));
}
getAllProjects() {
return this.ProjectListRef;
}
getFeaturedProjects() {
return this.featuredProjectList;
}
getProject(id: string) {
console.log(id);
return this.database.collection('projects').doc(id)
.ref.get().then( doc => doc.data() );
}
}
Project.component.ts
import { Component, OnInit, Injectable, Inject } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { tap } from 'rxjs/operators';
import { ProjectService } from '../../app/services/project.service';
import { AngularFirestore } from 'angularfire2/firestore';
import { Project } from '../../models/project';
import { DOCUMENT } from '#angular/common';
#Injectable()
#Component({
selector: 'app-project-page',
templateUrl: './project-page.component.html',
styleUrls: ['./project-page.component.scss']
})
export class ProjectPageComponent implements OnInit {
project: Project;
projectId: any;
projectRef: any;
constructor(#Inject(DOCUMENT) private document: any, private router: Router,
private route: ActivatedRoute,
public database: AngularFirestore,
private projectService: ProjectService
) {
}
ngOnInit() {
// print out the data from the route resolver
this.route.data.pipe(
tap(console.log))
.subscribe(
data => this.project = data['project']
);
}
goToWebsite(url) {
this.document.location.href = url;
}
}
3. **ProjectResolver.ts**
import { ProjectService } from './../../app/services/project.service';
import { Project } from './../project';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { Observable } from 'rxjs';
import { Injectable } from '#angular/core';
#Injectable()
export class ProjectResolver implements Resolve<Project> {
constructor(private projectService: ProjectService) {
}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<Project>|Promise<any> {
return this.projectService.getProject(route.params['id']);
}
}
Application Routes
import { AddLeadPageComponent } from './add-lead-page/add-lead-page.component';
import { GoogleAdsPageComponent } from './google-ads-page/google-ads-page.component';
import { WebAppsPageComponent } from './web-apps-page/web-apps-page.component';
import { BrandedWebsitesPageComponent } from './branded-websites-page/branded-websites-page.component';
import { ServiceOverviewPageComponent } from './service-overview-page/service-overview-page.component';
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePageComponent } from './home-page/home-page.component';
import { AboutPageComponent } from './about-page/about-page.component';
import { BlogPageComponent } from './blog-page/blog-page.component';
import { WebServicesPageComponent } from './web-services-page/web-services-page.component';
import { SEMPageComponent } from './sempage/sempage.component';
import { ContactPageComponent } from './contact-page/contact-page.component';
import { AllProjectsPageComponent } from './all-projects-page/all-projects-page.component';
import { ResearchServicePageComponent } from './research-service-page/research-service-page.component';
import { ProjectPageComponent } from './project-page/project-page.component';
import { TeamPageComponent } from './team-page/team-page.component';
import { NewProjectComponent } from './new-project/new-project.component';
import { DigitalMarketingPageComponent } from './digital-marketing-page/digital-marketing-page.component';
import { ProjectResolver } from '../models/resolvers/project.resolver';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomePageComponent},
{ path: 'about', component: AboutPageComponent},
{ path: 'blog', component: BlogPageComponent},
{ path: 'team', component: TeamPageComponent},
{ path: 'portfolio', component: AllProjectsPageComponent},
{ path: 'services', component: ServiceOverviewPageComponent},
{ path: 'project/:id', component: ProjectPageComponent, resolve: { project: ProjectResolver}},
{ path: 'brand-strategy', component: ResearchServicePageComponent},
{ path: 'digital-strategy', component: DigitalMarketingPageComponent},
{ path: 'custom-websites', component: BrandedWebsitesPageComponent},
{ path: 'web-apps', component: WebAppsPageComponent},
{ path: 'google-ads', component: GoogleAdsPageComponent},
{ path: 'web-design-development', component: WebServicesPageComponent},
{ path: 'search-engine-marketing', component: SEMPageComponent},
{ path: 'start-new-project', component: ContactPageComponent},
{ path: 'new-project', component: NewProjectComponent},
// post trial
{ path: 'posts/add', component: AddLeadPageComponent},
{ path: 'posts/add/:id', component: AddLeadPageComponent},
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled'})
],
exports: [RouterModule]
})
export class AppRoutingModule { }
You don't have any error in your angular code. The problem you are facing is that the urls are not being rewritten to index.html. You need to configure this in your Firebase settings(firebase.json). This is the easiest and most common configuration:
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

Cannot read property 'path' of undefined in Angular 2

I'm getting error:
Cannot read property 'path' of undefined
when I go to login page.Login page is separate template from home layout.then I created login.component.ts as <router-outlet> and auth.component.ts for my login page.
But home page working fine. error occur only load separate login page:
This is my folder structure:
login.component.ts:
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
login.route.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { NoAuthGuard } from '../no-auth-guard.service';
import { AuthComponent } from '../login/auth.component';
export const AUTH_ROUTES: Routes = [
{
path: '', component: AuthComponent,// canActivate: [NoAuthGuard]
},
{
path: 'login', component: AuthComponent,// canActivate: [NoAuthGuard]
},
{
path: 'register', component: AuthComponent,// canActivate: [NoAuthGuard]
}
]
login.route.html:
<router-outlet></router-outlet>
auth.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import { Errors, UserService } from '../../shared';
import { UserLogin } from '../../shared/models';
#Component({
selector: 'auth-page',
styleUrls: ['./auth.component.css'],
templateUrl: './auth.component.html'
})
export class AuthComponent implements OnInit {
authLoginForm: FormGroup;
authRegisterForm: FormGroup;
constructor(private route: ActivatedRoute, private router: Router, private userService: UserService, private fb: FormBuilder) {
// use FormBuilder to create a form group
-- some code here
// end use FormBuilder to create a form group
}
ngOnInit() {}
userLogin() { }
userRegister() {}
}
app-routing.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { NoAuthGuard } from './auth/no-auth-guard.service';
import { HomeAuthResolver } from './layout/home-auth-resolver.service';
import { LoginComponent, AUTH_ROUTES } from './auth/index';
import {LayoutComponent, PUBLIC_ROUTES } from './layout/index';
const routes: Routes = [
{ path: 'login', component: LoginComponent,data: { title: 'Public Views' }, children: AUTH_ROUTES },
{ path: 'register', component: LoginComponent,data: { title: 'Public Views' }, children: AUTH_ROUTES },
{ path: '', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES },
{ path: '**', redirectTo: 'home' }
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
This problem lies in the ambiguity of your routing scheme. It's also worth noting the Routes is an array and thus ordered. Routes are evaluated in order they are defined in that array.
So move your empty route (path: '') in login.route.ts to the last position in the AUTH_ROUTES array.

Categories

Resources