我有一个角度4应用程序,在我将Router Guard(AuthGuard)应用到我的主页路由后,它不会重定向到主页。有人可以帮我弄清楚我的代码中是否存在任何问题。
app.module.ts
的一部分RouterModule.forRoot([
{ path: '', component: HomeComponent, canActivate: [AuthGuard]},
{ path: 'login-local', component: LoginFormComponent},
{ path: 'members-signup/:id',
component: MembersOnlySignupComponent,
canActivate: [AuthGuard, MemberAuthGuard]
},
{ path: 'members-signup',
component: MembersOnlySignupComponent
}
])],
providers: [
AuthService,
AuthGuard,
MemberAuthGuard,
....
{ provide: APP_INITIALIZER, useFactory: userProviderFactory, deps: [UserService], multi: true }
]
}}
export class AppModule {
}
export function userProviderFactory(provider: UserService) {
return () => {
let uid = localStorage.getItem('userId');
let uTypeId = localStorage.getItem('userTypeId');
if(uid)
provider.getUserByIdAsPromise(uid);
}
}
登录-form.component.ts
import { Router, ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { Location } from '@angular/common';
@Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent implements OnInit {
returnUrl;
constructor(private auth: AuthService, private route: ActivatedRoute,
private router: Router, private location: Location) { }
ngOnInit() {
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
login(credentials) {
if(credentials) {
this.auth.loginLocal(credentials.username, credentials.password)
.then(r => {
this.router.navigate(['/']);
})
.catch(r => {
this.router.navigate(['/login-local'])
});
}
else {
this.router.navigate(['/login-local']);
}
}
}
AuthService.ts
的登录方法async loginLocal(用户名:字符串,密码:字符串){
let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';
localStorage.setItem('returnUrl', returnUrl);
console.log("login credentials > " + username + ", " + password);
let md5Pass = Md5.hashStr(password).toString().trim();
let loggedInUser: User;
this.afs.collection('user', ref => ref.where('username', '==', username)
.where('password', '==', md5Pass)).snapshotChanges().take(1).subscribe(users => {
users.map(u => {
let dispatch = this.ngRedux.dispatch;
const id = u.payload.doc.id;
const data = u.payload.doc.data();
loggedInUser = { id, ...data } as User;
//store in local storage
localStorage.setItem('userId', id);
localStorage.setItem('userTypeId', loggedInUser.usertypeid);
if (loggedInUser) {
let fullName = loggedInUser.firstname + ' ' + loggedInUser.lastname;
if (loggedInUser.clubid) {
dispatch({
type: GET_CLUB_USER_LOGIN_STATE,
payload: {
displayUserName: fullName,
userId: loggedInUser.id,
username: loggedInUser.username,
photoUrl: loggedInUser.imageurl,
userTypeId: loggedInUser.usertypeid,
clubId: loggedInUser.clubid
}
});
}
else {
dispatch({
type: GET_MO_USER_AND_MEMBER_LOGIN_STATE,
payload: {
displayUserName: fullName,
userId: loggedInUser.id,
username: loggedInUser.username,
photoUrl: loggedInUser.imageurl,
userTypeId: loggedInUser.usertypeid
}
});
}
}
else {
console.log('false');
}
});
});
if(await loggedInUser)
return loggedInUser;
}
AuthGuard.ts
@Injectable()
export class AuthGuard implements CanActivate{
@select('displayUserName') displayUserName;
constructor(private auth: AuthService, private router: Router) { }
canActivate(route, state: RouterStateSnapshot) {
if(localStorage.getItem('userTypeId')) {
return true;
}
this.router.navigate(['/login-local'], {queryParams: {returnUrl: state.url}});
return false;
}
}