gpt4 book ai didi

Angular 8 显示没有错误的空白页

转载 作者:行者123 更新时间:2023-12-01 03:06:09 28 4
gpt4 key购买 nike

我正在开发一个 Angular 8 应用程序,它将使用 JWT token 身份验证登录到 .Net Core Rest API。

当我启动应用程序时,应用程序编译成功,没有错误。但是,当我打开 http://localhost:4200出现一个空白页。

这是app-routing.module.ts文件:

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

这是 app.component.ts文件:

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']);
}
}

这是 login.component.ts文件:

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;
});
}
}

编辑:

这是 auth.guard.ts文件:

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

我希望看到登录页面,但在我输入 ng serve 后会出现一个空白页面并打开 http://localhost:4200

最佳答案

好吧,这只是发生在我身上,可能会帮助其他人:

  • 已安装 @nestjs/ng-universal $ ng add @nestjs/ng-universal
  • 我正在处理的 angular 项目已经安装了@nguniversal,我已经手动卸载了我发现的所有相关内容。
  • 所以当我安装这个新包时,它再次修改了/src/main.ts,包装了两次 boostrap。
  • document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('DOMContentLoaded', () => {
    platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.error(err));
    });
    });

    这给了我一个空白页运行 $ ng serve没有错误,没有消息,没有任何内容,只有一个白色和令人讨厌的页面。
    删除其中之一后 document.addEventListener( ...包装器,它奏效了!

    关于Angular 8 显示没有错误的空白页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304940/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com