Angular 8 showing blank page with no errors
Asked Answered
F

14

22

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

Forborne answered 1/8, 2019 at 8:35 Comment(4)
What was the issue ? I guess you solved it by now and I get the same issue today...Century
here my solution, hope it helpsOscine
Check your browser console, the cause of the error is usually displayed there.Discourage
@EmmanuelAliji there is no error in the console in my case. and no error from my API.Kuenlun
F
11

Ok, this just happend to me and may help someone else:

  • installed @nestjs/ng-universal $ ng add @nestjs/ng-universal
  • the angular project I´m working on already had @nguniversal installed, I´ve uninstalled manually all I´ve found related to it.
  • so when I´ve installed this new package, it modified the again /src/main.ts, wrapping twice the boostrap.
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!

Fjord answered 7/12, 2019 at 22:56 Comment(2)
@guillefd, for newbie-ism reasons, I need a digest. So I should: 1) install with $ ng add @nestjs/ng-universal 2) add imports to app.module as shown at ng-universal repo 3) replace main.ts code for document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => { platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); }); }); Is that it? Thanks a lot in advanceEgyptian
If this does not work, check your browser console. The error is usually displayed there.Discourage
S
3

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.

Swett answered 21/11, 2019 at 20:9 Comment(1)
This helped me more than the other answers. Actually found out it was OBS running in the background that caused my angular app just to appear as white. I assume it's something to do with rendering. The same issue on Edge, Chrome, and Brave (All Chromium based), Firefox seemed to work.Bravery
J
3

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.

Jowett answered 11/2, 2020 at 14:13 Comment(0)
N
2

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.

Nila answered 1/8, 2019 at 9:48 Comment(2)
I edited the question and added the AuthGuard file.Can you check the code again?Forborne
If you need more code just tell me and I will edit the question and write more codeForborne
E
1

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

Expanded answered 10/1, 2020 at 19:58 Comment(0)
C
1

You can also check to see if your selectors have been named correctly after refactoring

Coulisse answered 28/10, 2021 at 23:30 Comment(0)
D
0

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';
Domenicadomenico answered 1/8, 2019 at 9:31 Comment(0)
F
0

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 { }
Fenton answered 1/8, 2019 at 9:46 Comment(2)
Sorry but I have tried both solutions but none of the solutions are workingForborne
If you need more code just tell me and I will edit the question and write more codeForborne
V
0

In my case I just named the file app.routing.ts instead of app-routing.module.ts. By fixing that it worked.

Vasiliu answered 17/12, 2020 at 9:56 Comment(0)
O
0

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" }

Ochone answered 6/3, 2021 at 4:37 Comment(0)
I
0

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

Inpour answered 19/10, 2022 at 11:10 Comment(0)
W
0

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)

Waac answered 30/3, 2023 at 12:41 Comment(0)
V
0

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>
Var answered 13/6 at 11:55 Comment(0)
V
-3

Missing <router-outlet></router-outlet> in your view? (Documentation)

Vitavitaceous answered 1/8, 2019 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.