Angular 5登录后不重定向
我使用Angular 5实现了一个使用令牌的身份验证系统 当我尝试在登录表单上进行身份验证时,它会启动身份验证表单,但随后它会刷新页面: 这是我的项目文件结构:Angular 5登录后不重定向,angular,authentication,angular-ui-router,httprequest,angular5,Angular,Authentication,Angular Ui Router,Httprequest,Angular5,我使用Angular 5实现了一个使用令牌的身份验证系统 当我尝试在登录表单上进行身份验证时,它会启动身份验证表单,但随后它会刷新页面: 这是我的项目文件结构: src ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── auth │ │ ├──
src
├── app
│ ├── app.component.css
│ ├── app.component.html
│ ├── app.component.spec.ts
│ ├── app.component.ts
│ ├── app.module.ts
│ ├── auth
│ │ ├── auth.guard.spec.ts
│ │ ├── auth.guard.ts
│ │ ├── auth.service.spec.ts
│ │ ├── auth.service.ts
│ │ └── token.response.ts
│ ├── dashboard
│ │ ├── dashboard.component.css
│ │ ├── dashboard.component.html
│ │ ├── dashboard.component.spec.ts
│ │ └── dashboard.component.ts
│ ├── login-form
│ │ ├── login-form.component.css
│ │ ├── login-form.component.html
│ │ ├── login-form.component.spec.ts
│ │ └── login-form.component.ts
│ └── navbar
│ ├── navbar.component.css
│ ├── navbar.component.html
│ ├── navbar.component.spec.ts
│ └── navbar.component.ts
以下是主要的项目文件:
app.component.html:
<router-outlet></router-outlet>
<div class="container">
<div class="card card-container">
<p id="profile-name" class="profile-name-card">OneBets</p>
<form class="form-signin" (submit)="loginUser($event)">
<span id="reauth-email" class="reauth-email"></span>
<input type="text" id="inputEmail" class="form-control" placeholder="User" required autofocus>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block btn-signin" type="submit">Sign in</button>
</form>
<a href="#" class="forgot-password">
Forgot the password?
</a>
</div>
</div>
login-form.component.html:
<router-outlet></router-outlet>
<div class="container">
<div class="card card-container">
<p id="profile-name" class="profile-name-card">OneBets</p>
<form class="form-signin" (submit)="loginUser($event)">
<span id="reauth-email" class="reauth-email"></span>
<input type="text" id="inputEmail" class="form-control" placeholder="User" required autofocus>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block btn-signin" type="submit">Sign in</button>
</form>
<a href="#" class="forgot-password">
Forgot the password?
</a>
</div>
</div>
auth.service.ts:
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs/Observable';
import { NgModule } from '@angular/core';
import { TokenResponse } from './token.response'
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class AuthService {
constructor(
private cookieService: CookieService, private http:HttpClient,
private router: Router) { }
get token() {
if (this.cookieService.check('token')) {
return('Bearer ' + this.cookieService.get('token'))
}
else {
return null;
}
}
set token(newToken) {
this.cookieService.set('token', newToken)
}
getApiHttpOptions(token=false) {
if (token) {
console.log('headers are:', { 'Content-Type': 'application/json' });
return { headers: new HttpHeaders(
{ 'Content-Type': 'application/json' }) }
} else {
console.log('headers are:', { 'Content-Type': 'application/json',
'Authorization': this.token });
return { headers: new HttpHeaders(
{ 'Content-Type': 'application/json',
'Authorization': this.token }) }
}
}
removeTokens() {
console.log('Removing tokens.');
if (this.cookieService.check('token')){
this.cookieService.delete('token');
}
if (this.cookieService.check('refreshToken')){
this.cookieService.delete('refreshToken');
}
return true;
}
get isLoggedIn() {
// Check if there's a session token on the cookie
if (this.cookieService.check('refreshToken')) {
return true;
} else {
return false;
}
}
authenticate(user, passwd) {
console.log('Starting authentication');
return this.http.post('/api/token/', {'username': user, 'password': passwd},
this.getApiHttpOptions(true))
}
}
auth.guard.ts:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.log('AuthGuard');
if(this.auth.isLoggedIn) {
return true;
} else {
window.alert("You don't have permission to view this page");
this.router.navigate(['']);
return false;
}
}
}
从'@angular/core'导入{Injectable};
从'@angular/Router'导入{Router};
从'@angular/router'导入{CanActivate,ActivatedRouteSnapshot,RouterStateSnashot};
从“rxjs/Observable”导入{Observable};
从“/auth.service”导入{AuthService};
@可注射()
导出类AuthGuard实现了CanActivate{
构造函数(私有身份验证:身份验证服务,私有路由器:路由器){}
激活(
下一步:ActivatedRouteSnapshot,
状态:RouterStateSnashot):可观察的|承诺|布尔值{
console.log('AuthGuard');
if(this.auth.isLoggedIn){
返回true;
}否则{
警告(“您没有查看此页面的权限”);
这个.router.navigate(['']);
返回false;
}
}
}
附言:
我刚刚开始前端开发,我正在努力学习Angular 5
我已经通过Django Rest开发了身份验证后端,我100%确信它正在工作。在
登录表单.component.ts
下的登录用户
,作为第一行添加:e.preventDefault()
表单正在向当前url提交一个硬获取请求,因为您有一个提交按钮。我还遇到了if条件直接跳到else的问题,因为方法调用末尾没有()的问题
if(this.auth.isLoggedIn)到if(this.auth.isLoggedIn())工作正常!谢谢