我有一个有两个组件“登录”和“家”的角度应用程序。我想保护 home 组件,直到用户登录。
我有一个具有布尔变量“isUserLoggedIn”的服务。根据这个变量的值,我保护我的组件。
网络服务-
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
@Injectable()
export class NetworkService {
private isUserLoggedIn = false;
constructor(private _http:Http) {
}
getUserLoggedIn(){
console.log("network service ... isUserLoggedIn = "+this.isUserLoggedIn);
return this.isUserLoggedIn;
}
setUserLoggedIn(){
this.isUserLoggedIn = true;
console.log("service layer : setUserLoggedIn called .... isUserLoggedIn = "+this.isUserLoggedIn);
}
}
我的身份验证代码
import { NetworkService } from './../services/network.service';
import { Router,CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthGuard implements CanActivate{
constructor(private networkservice:NetworkService, private router:Router){
}
canActivate(){
console.log("canActivate called : userLoggedIn = "+this.networkservice.getUserLoggedIn());
if(this.networkservice.getUserLoggedIn()){
return true;
}
else{
this.router.navigate(['/login']);
return false;
}
}
}
登录组件
import { Component, OnInit } from '@angular/core';
import { NetworkService } from './../services/network.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers : [NetworkService]
})
export class LoginComponent implements OnInit {
constructor(private networkservice : NetworkService, private router: Router) {
}
ngOnInit() {
}
onSubmit(value:any){
console.log("user = "+value.username+" password = "+value.password);
if(value.username == "user" && value.password == "user"){
this.networkservice.setUserLoggedIn();
this.router.navigate(['/home']);
}
else{
alert("Username or Password did not match !!!");
}
}
}
路由器
import { AuthGuard } from './guards/auth.guard';
import { LoginComponent } from './login/login.component';
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
export const router: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full'},
{ path: 'home', component: HomeComponent, canActivate:[AuthGuard]},
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
最后是我的应用模块
import { AuthGuard } from './guards/auth.guard';
.....
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
DataTablesModule,
Ng2UploaderModule,
routes
],
providers: [NetworkService,AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
现在我使用硬编码文本作为用户名和密码。
我的问题是,即使登录组件将服务的“isUserLoggedIn”变量设置为“true”,auth-guard 仍然认为它是 false。因此我无法导航到“主页”组件。