首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2 auth guard使用observable跟踪当前用户

Angular2 auth guard使用observable跟踪当前用户
EN

Stack Overflow用户
提问于 2017-07-06 12:04:42
回答 2查看 1.3K关注 0票数 0

我是Angular的新手,我正在尝试在我的应用程序中编写一个身份验证保护,我知道我每次都可以访问我的服务器,并获得有关登录用户的会话信息。但我想在整个应用程序中跟踪登录的用户……

app.component.ts

代码语言:javascript
复制
  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

代码语言:javascript
复制
@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

代码语言:javascript
复制
@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

代码语言:javascript
复制
@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中定义的认证服务是不同的实体吗?

EN

回答 2

Stack Overflow用户

发布于 2017-07-06 13:04:13

代码语言:javascript
复制
return this.authService.isAuthenticated.take(1)

始终返回第一个值。

take的

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

将其更改为

代码语言:javascript
复制
return this.authService.isAuthenticated;
票数 0
EN

Stack Overflow用户

发布于 2018-08-21 17:13:23

这可能是因为您从一个空的(或刚初始化的)主题创建了可观察对象。Observable是在实例化时将值一次带入主题中。如果你想把它当做一个可观察对象使用,在一个方法或getter中实例化它。

代码语言:javascript
复制
get isAuthenticated ()  { return this.isAuthenticatedSubject.asObservable(); }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44939623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档