注入这里是我的代码AuthService总是在默认状态
import {User} from '../models/user';
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions, Response} from '@angular/http';
import {AuthHttp} from 'angular2-jwt';
import {Router} from '@angular/router';
import {Config} from '../app.constants';
import {Observable, ReplaySubject} from 'rxjs/Rx';
@Injectable()
export class AuthService {
public currentUser: ReplaySubject<User> = new ReplaySubject<User>(1);
public loggedIn = false;
constructor(public http: Http,
public authHttp: AuthHttp,
private router: Router) {
}
public setCurrentUser(user: User) {
this.loggedIn = true;
this.currentUser.next(user);
}
}
此路由
export const routes: Routes = [
{
children: [
{
component: HomeComponent,
path: ''
},
{
canActivate: [CanActivateGuard],
component: UploadComponent,
path: 'upload',
},
{
component: RegisterComponent,
path: 'register'
},
{
component: LoginComponent,
path: 'login'
},
],
component: WebComponent,
path: '',
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class WebRoutingModule {
}
时使用的登录验证码设置this.loggedIn为true
let user = new User(data.user);
this._auth.setCurrentUser(user);
问题发生在登录后
我在这里的调试结果
上web.component.ts我加在toggleSearchInput方法console.log(this._auth)
toggleSearchInput() {
console.log(this._auth)
this.searchInputExpanded = !this.searchInputExpanded;
}
当我点击该按钮,它控制台登录到我loggedd正确_auth在=真
上guard.service.ts我加入on canActivate方法console.log(this._auth)
public canActivate() {
console.log(this._auth)
if (!this.logged) {
this.router.navigate([ 'login' ]);
}
return this.logged;
}
并检查控制台e每次我点击上传..它控制台我身份验证服务就像没有发生它,登录= false即使登录后...你知道为什么这么说吗?
为什么不改变
你有多个模块磨片你使用你的服务? –
这里是完整的代码https://github.com/MoustafaElkady/You360-Web-Client/tree/master/src/app在src/app/services/guard.service.ts中的问题 当我在src中使用它时/app/web/web-routing.module.ts –