I am developing an Angular 8 application that will login to a .Net Core Rest API using JWT Token Authentication.
When I start the application the application compiles successfully with no errors. However, when I open http://localhost:4200 a blank page appears.
Here is the app-routing.module.ts
file:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login';
import { HomeComponent } from './home';
import { AppComponent } from './app.component';
import { AuthGuard } from './_helpers';
const routes: Routes = [
{path: '',component:AppComponent,canActivate: [AuthGuard]},
{path:'login',component:LoginComponent},
{path: '**',redirectTo:''}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here is the app.component.ts
file:
import { Component ,ViewChild,OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { Router } from '@angular/router';
import {Sort} from '@angular/material';
import { Log } from './log';
import {MatPaginator,MatSort,MatTableDataSource} from '@angular/material';
import { AuthenticationService } from './_services';
import { User } from './_models';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
currentUser: User;
public isViewable:boolean;
constructor(private apiService: ApiService,private router: Router,private authenticationService: AuthenticationService){
this.authenticationService.currentUser.subscribe(x => this.currentUser = x);
}
dataSource=new MatTableDataSource<Log>();
displayedColumns: string[] = ['message','create_Date','log_Type'];
@ViewChild(MatSort,{static:true}) sort: MatSort;
ngOnInit(){
this.dataSource.sort=this.sort;
this.apiService.getLogs().subscribe((res)=>{
this.dataSource.data=res;
});
}
public onSortData(sort:Sort){
let data=this.dataSource.data.slice();
if(sort.active && sort.direction!==''){
data=data.sort((a:Log,b:Log)=>{
const isAsc=sort.direction==='asc';
switch(sort.active){
case 'message': return this.compare(a.message,b.message,isAsc);
case 'create_Date':return this.compare(a.create_Date,b.create_Date,isAsc);
case 'log_Type':return this.compare(a.log_Type,b.log_Type,isAsc);
default: return 0;
}
});
}
this.dataSource.data=data;
}
private compare(a,b,isAsc){
return (a.toLowerCase() < b.toLowerCase() ? -1 : 1) * (isAsc ? 1:-1);
}
public toggle():void{
this.isViewable=!this.isViewable;
this.apiService.getLogs().subscribe((res)=>{
this.dataSource.data=res;
});
}
logout() {
this.authenticationService.logout();
this.router.navigate(['/login']);
}
}
Here is the login.component.ts
file:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AuthenticationService } from '../_services';
@Component({ templateUrl: 'login.component.html' })
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
error = '';
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService
) {
// redirect to home if already logged in
if (this.authenticationService.currentUserValue) {
this.router.navigate(['/']);
}
}
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.authenticationService.login(this.f.username.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.error = error;
this.loading = false;
});
}
}
Edit:
Here is the auth.guard.ts
file:
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../_services';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
I expect to see the login page but a blank page appears after I type ng serve
and open http://localhost:4200