Reputation: 521
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
Upvotes: 23
Views: 60377
Reputation: 1
Verify Base Href Ensure that the baseHref is set correctly in the index.html file if your application is hosted in a subdirectory.
***index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Make a Trip</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
Upvotes: 0
Reputation: 178
In my case, probably the localhost was active somehow. I searched for the port number in the files (e.g. : 4200) and changed it to another port number (e.g. 4201)
Upvotes: 0
Reputation: 149
In my case in the template I had an all-wrapping container with ngIf="..." and its condition was false thus not a single line of html was rendered
Upvotes: 0
Reputation: 111
You can also check to see if your selectors have been named correctly after refactoring
Upvotes: 1
Reputation: 4518
This issue is generally hard to identify. However, it is probably linked to an error in code which gets executed during application initiation. This most probably includes initiation of any kind of authentication module.
Check/debug your app.module.ts
and all things called from there - like APP_INITIALIZER
.
Upvotes: 3
Reputation: 21
The issue with my code was I have used the keycloak installation config object as it is i.e
{
"realm": "demo",
"auth-server-url": "http://localhost:8180/auth/",
"ssl-required": "external",
"resource": "local",
"public-client": true,
"confidential-port": 0,
"clientId": "local"
}
But it was wrong, the correct one was as below:
{ url: "http://localhost:8180/auth/", realm: "demo", clientId: "local" }
Upvotes: 0
Reputation: 31
In my case I just named the file app.routing.ts
instead of app-routing.module.ts
. By fixing that it worked.
Upvotes: 0
Reputation: 147
1.- Open tags. Check if you have the properly closed tags in the html files. In my case the problem was because in one component I had an extra </div>
.
2.- Undeclared inputs. Check if you are trying to pass an input that is not declared in the component, for example <app-component [var1]="123"> </app-component>
, in your component you must necessarily have the input declared @Input () var1;
3.- keys to print {{}}
empty in some html file
4.- undeclared properties with angular tags. For example in a <input [anyWord]>
where [anyWord] is not a valid entry
Upvotes: 1
Reputation: 2023
Ok, this just happend to me and may help someone else:
$ ng add @nestjs/ng-universal
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
});
});
This give me a blank page running $ ng serve
with no error, no message, no nothing, just a white and nasty page.
After deleting one of the document.addEventListener( ...
wrappers, it worked!
Upvotes: 11
Reputation: 1645
Recently I faced the same issue in the chrome browser, after updating chrome version this issue fixed. You can verify this issue related to the browser or not, by cross-checking in other browsers like IE or Safari.
Edit: Additional to this, please try by disabling some extensions in chrome. Make sure you restart the browser once you disabled the extensions. Once it is working enable required extensions.
Upvotes: 3
Reputation: 2158
I facing same issue so i just refresh page twice and that's works but you can try this,
in your routes if angular can't find any routes that you've typed on you shoul redirect to
PageNotFoundComponent
, so create a component PageNotFoundComponent
and redirect to that component because you don't handle at all other routes other then those that you specified
{path: '**',redirectTo:''} // instead of this
{path: '**', redirectTo:'PageNotFoundComponent'} // add this
Or you may try this with { useHash: true }
in routerConfig and all routes will use #/login
and you can use this just for development mode and when you want to publish you can remove this config { useHash: true }
@NgModule({
imports: [
...
...
RouterModule.forRoot(routes, { useHash: true }) // .../#/crisis-center/
],
...
})
export class AppModule { }
Upvotes: 0
Reputation: 370
Please check your 'AuthGuard'.Check whether its returning true. Since your default root has been protected and if it returns false then i think thats why your page is not loading.
Upvotes: 2
Reputation: 1521
Maybe you are using an unsupported version of IE?
Try Chrome, a later IE or Firefox, etc. Alternatively, you can uncomment the browser polyfills in polyfills.ts
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/array';
import 'core-js/es6/date';
import 'core-js/es6/function';
import 'core-js/es6/map';
import 'core-js/es6/math';
import 'core-js/es6/number';
import 'core-js/es6/object';
import 'core-js/es6/parse-float';
import 'core-js/es6/parse-int';
import 'core-js/es6/regexp';
import 'core-js/es6/set';
import 'core-js/es6/string';
import 'core-js/es6/symbol';
import 'core-js/es6/weak-map';
Upvotes: 0
Reputation: 681
Missing <router-outlet></router-outlet>
in your view? (Documentation)
Upvotes: -3