Angular2 - canActivate没有从AuthService获取值

时间:2016-08-04 00:57:43

标签: authentication angular

尝试使用angular-2创建登录功能,其中我使用了一个登录组件,authservice,logingard with canActive。

在关注angular2文档的示例时,我没有获得保护文件中登录的值,并且每次都要求登录

在此处发布示例代码 AuthService

export class AuthService {
  loggedIn: boolean = false;

  isLoggedIn() {
    return this.loggedIn;
  } 

  login(credentials) {
    let user = JSON.stringify(credentials);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this._http.post(this._apiUrl, user, options)
                .map(res => res.json())
                .map((res) => {                     
                    this.loggedIn = true;
                  }
                  return res;
                });
  }}

Loggedin Guard

export class LoggedInGuard implements CanActivate {
  constructor(private _auth: AuthService, private _router: Router) {}

  canActivate() {
    //Get problem here. Everytime this comes false
    if(this._auth.isLoggedIn()) { return true; }

    this._router.navigate(['login']);
  }
}

登录组件

export class LoginComponent {
  constructor(private userService: AuthService, private router: Router) {}

  onSubmit(email, password) {
    this.userService.login(email, password).subscribe((result) => {
      if (result) {
        this.router.navigate(['']);
      }
    });
  }
}

顺便说一下,以下的例子 https://medium.com/@blacksonic86/angular-2-authentication-revisited-611bf7373bf9#.723a4ssji 没有localstorage

0 个答案:

没有答案
相关问题