我正在尝试实施一个网站,以便在使用用户名“Admin@gmail.com”和密码“Admin”登录后,用户将登录并重定向到主页。但是,如果用户提供了除指定值以外的任何值,则网站将抛出错误。
如何在角度2中编写一段代码来做这样的事情?
以下是我的login.component.ts文件:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form">
<input type="text" class="vchange" />
<input type="text" class="vchange" />
<a href="#" class="btn btn-success vsubmit" onmousedown="return false;">Submit</a>
</div>
我的login.component.html文件是:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../Services/auth.service';
@Component({
templateUrl: './login.component.html',
})
export class LoginComponent {
message: string;
constructor(public authService: AuthService, public router: Router) {
this.setMessage();
}
setMessage() {
this.message = 'Logged ' + (this.authService.isLoggedIn ? 'in' : 'out');
}
login() {
this.message = 'Trying to log in ...';
this.authService.login().subscribe(() => {
this.setMessage();
if (this.authService.isLoggedIn) {
// Get the redirect URL from our auth service
// If no redirect has been set, use the default
let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/home';
// Redirect the user
this.router.navigate([redirect]);
}
});
}
logout() {
this.authService.logout();
this.setMessage();
}
}
答案 0 :(得分:0)
您可以使用Route Guard。它将解决您的解决方案。
// src / app / auth / auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
// src / app / app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '' }
];