【问题标题】:Angular2 auth guard keeps track of current user with observableAngular2 auth guard 使用 observable 跟踪当前用户
【发布时间】: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


【解决方案1】:
return this.authService.isAuthenticated.take(1)

总是返回第一个值。

take 的文档:从可观察序列的开头返回指定数量的连续元素

改成

return this.authService.isAuthenticated;

【讨论】:

  • 谢谢,我将如何使用它来访问整个应用程序的布尔值?因为当我订阅 isAuthenticated 时,即使我将其设置为 true,返回的值也始终为 false
  • 为什么设置为 1 ,使用 truefalse
  • 我没有将其设置为 1 tho,在登录时 this.isAuthenticatedSubject.next(true);
  • 你能用BehaviorSubject代替ReplaySubject试试
  • 嗯,我想我的问题是如果我在 app.module 中将 isAuthenticated 设置为 true,我将如何从其他模块中检索该值?有可能吗?
【解决方案2】:

这可能是因为您从一个空的(或刚刚初始化的)主题创建了 observable。当你实例化它时,Observable 会一次性将值带入主题。 如果您想将其用作 Observable,请将其实例化为方法或 getter。

get isAuthenticated ()  { return this.isAuthenticatedSubject.asObservable(); }

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多