【发布时间】:2017-12-09 21:54:45
【问题描述】:
我对 Angular 还是很陌生 我正在尝试在我的应用程序中编写身份验证保护, 我知道我每次都可以访问我的服务器并获取有关已登录用户的会话信息。 但我想在整个应用程序中跟踪登录用户...
app.component.ts
export class AppComponent implements OnInit {
title = 'APPTITLE';
logged_in = true;
constructor(private authService: AuthenticationService){}
ngOnInit(){
this.authService.isAuthenticated.take(1)
.subscribe(res => {
console.log(res);
this.logged_in = res});
}
}
AuthenticationService.ts
@Injectable()
export class AuthenticationService {
private currentUserSubject = new BehaviorSubject<IUser>(<IUser>{});
public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();
private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
public isAuthenticated = this.isAuthenticatedSubject.asObservable();
private isAdminSubject = new ReplaySubject<boolean>(1);
public isAdmin = this.isAdminSubject.asObservable();
constructor(private http: HttpService) {
this.isAuthenticatedSubject.next(false);
this.isAdminSubject.next(false);
}
login(username: string, password: string, onSuccess: (data) => void, onError: (data) => void=null): any {
this.isAuthenticatedSubject.next(true);
let query_url = 'login';
let payload = JSON.stringify({username: username, password: password});
return this.http.post(query_url, payload)
.subscribe(user => {
this.currentUserSubject.next(user);
this.isAuthenticatedSubject.next(true);
if (user.usertype == 'admin') this.isAdminSubject.next(true);
onSuccess(user);
},
error => {
if (onError){
onError(error);
}
});
}
logout() {
let query_url = 'logout';
return this.http.post(query_url, null)
.subscribe(res => {
this.currentUserSubject.next(null);
this.isAuthenticatedSubject.next(false);
this.isAdminSubject.next(false);
})
}
}
auth-guard.ts
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private router: Router, private authService: AuthenticationService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>{
return this.authService.isAuthenticated.take(1)
}
}
login.component.ts
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthenticationService]
})
export class LoginComponent implements OnInit {
error_message: string = 'Login Unsuccessful'
login_info: any = {};
constructor(public router: Router,
private authenticationService: AuthenticationService) {
}
ngOnInit() {
}
formSubmitted(data): void {
this.login(data.username, data.password);
}
login(username, password) {
event.preventDefault();
this.authenticationService.login(username, password, (data) => {
console.log(data);
},
(err) => {
console.log(err);
})
}
auth-guard 在这里总是会返回 false,我不知道为什么。 auth-guard 和 login 中定义的认证服务是不同的实体吗?
【问题讨论】:
-
你在应用中初始化了多少次服务。我的意思是添加一个 provider 。同时删除
take(1)
标签: angular authentication angular2-services