我正在尝试在登录用户时重定向另一个URL。
login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { LoginService } from '../services/login.service';
import { SessionService } from '../services/session.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: FormGroup;
err = false;
err_text: string;
err_message: string;
err_code: number;
constructor( public _login: LoginService,
private _session: SessionService,
private _router: Router ) { }
ngOnInit() {
this.form = new FormGroup({
user: new FormControl('', Validators.required ),
password: new FormControl( '', Validators.required )
});
}
login() {
if ( this.form.valid ) {
this._login.login( this.form.value )
.subscribe(
( res: any ) => {
this.err = false;
this._session.setLogin( res.data );
console.log('REDIRECT');
this._router.navigate(['/']);
},
( err: any ) => {
this.err = true;
this.err_text = err.statusText;
this.err_code = err.status;
this.err_message = err.error.message;
}
);
}
}
}
当观察对象正确返回我要重定向到“仪表板”的响应(此处尚未创建)时,我在this._router.navigate(['/']);
处出错
这是login.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { URL_BACKEND } from '../global/variables';
@Injectable({
providedIn: 'root'
})
export class LoginService {
constructor( private _http: HttpClient ) { }
login( data: any ) {
return this._http.post(`${ URL_BACKEND }/login.php`, data );
}
isLogged() {
return this._http.get(`${ URL_BACKEND }/login.php` );
}
}
我对此没有问题,可以正常工作。
这是routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { PagesComponent } from './pages/pages.component';
import { SessionGuard } from './services/guards/session.guard';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '',
canActivate: [SessionGuard],
component: PagesComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我正在使用session.guard.ts
保护根import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { LoginService } from '../login.service';
@Injectable({
providedIn: 'root'
})
export class SessionGuard implements CanActivate {
constructor( private _login: LoginService, private _router: Router ) {}
canActivate(): boolean {
let logged = false;
this._login.isLogged()
.subscribe(
( res: any ) => {
if ( res.data.logged ) {
logged = true;
} else {
logged = false;
this._router.navigate(['/login']);
}
},
( err: any ) => {
logged = false;
this._router.navigate(['/login']);
}
);
return logged;
}
}
问题是,当服务器在登录过程中返回true时,我想重定向到根路由,但是在登录时仍然静止。很奇怪,因为在我的Google控制台的“网络”标签中调用了Guard,服务器返回true,但是页面永不更改。
怎么了?