我正在开发一个 Angular 8 应用程序,它将使用 JWT 令牌身份验证登录到 .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 { }
Run Code Online (Sandbox Code Playgroud)
这是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']);
}
}
Run Code Online (Sandbox Code Playgroud)
这是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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
这是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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望看到登录页面,但在我输入ng serve并打开http://localhost:4200后会出现一个空白页面
gui*_*efd 11
好吧,这只是发生在我身上,可能会帮助其他人:
$ ng add @nestjs/ng-universaldocument.addEventListener('DOMContentLoaded', () => {
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
});
});
Run Code Online (Sandbox Code Playgroud)
这给了我一个空白页面$ ng serve,没有错误,没有消息,没有任何内容,只有一个白色和令人讨厌的页面。
删除其中一个document.addEventListener( ...包装器后,它起作用了!
| 归档时间: |
|
| 查看次数: |
25552 次 |
| 最近记录: |