Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 showing blank page with no errors

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

like image 675
freelancer86 Avatar asked Aug 01 '19 08:08

freelancer86


3 Answers

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!

like image 177
guillefd Avatar answered Nov 15 '22 23:11

guillefd


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.

like image 22
Yuri Avatar answered Nov 16 '22 01:11

Yuri


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.

like image 2
Andrew Rayan Avatar answered Nov 16 '22 00:11

Andrew Rayan