Angular 2:Observable只返回" false"

时间:2017-03-23 19:40:01

标签: angular

我使用以下代码验证登录:

auth.service.ts

import { User } from './user.interface';
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';

@Injectable()

export class AuthService {

  token: any;
  currentUser: any;

  constructor(private router: Router, private http: Http) {
    this.currentUser = JSON.parse(localStorage.getItem('currentUser-hb'));
  }
isAuthenticated() {
      const state = new Subject<any>();

      if (this.currentUser != null) {
        const token = this.currentUser.token;
        const body = JSON.stringify({token: token});
        return this.http.post('https://test.de/validatetoken', body)
          .map((response: Response) => {
            const authResponse = response.json().response;
            if (authResponse) {
              state.next(true);
              alert('Valid Token');
            } else {
              state.next(false);
              alert('No valid Token');
            }
            return state.asObservable();
          });
      }...

navigation.component.ts

isAuthenticated: any = false;
  constructor(private authService: AuthService, private router: Router) {
    this.authService.isAuthenticated().subscribe(
      data => console.log(data)
    );
    if (this.isAuthenticated !== false) {
      this.router.navigate(['']);
    }
  }

如果当前令牌有效,则auth.service会发出警报。但是,只要令牌有效,observable每次都会返回&#34; false&#34;我无法找到错误..

3 个答案:

答案 0 :(得分:1)

你有没有理由在这里使用主题?为什么不简单地返回truefalse?您正在订阅回复,因此每当isAuthenticated()被解雇时,您都会收到订阅中的回复...请尝试:

isAuthenticated() {
  return this.http.post('https://test.de/validatetoken', body)
    .map((response: Response) => {
       const authResponse = response.json().response;
       if (authResponse) {
          return true;
       } else {
          return false;
       }
    })
  }

和组件,可能会在OnInit中触发该方法,但我已经像你一样使用了构造函数。

isAuthenticated: any = false;

constructor(private authService: AuthService, private router: Router) {
   this.authService.isAuthenticated()
      .subscribe(data => {
         this.isAuthenticated = data;
         // check value of isAuthenticated inside subscription!
         if (this.isAuthenticated !== false) {
            this.router.navigate(['']);
         }
      });
  }

答案 1 :(得分:0)

isAuthenticated:any = false;构造函数(private authService:AuthService,private router:Router){this.authService.isAuthenticated()。subscribe(data =&gt; {console.log(data); this.isAuthenticated = data; if(this.isAuthenticated!== false){this.router.navigate(['']); }})}

未经测试,但这将解决您的问题。

答案 2 :(得分:0)

这是同步运行的,fyi:

if (this.isAuthenticated !== false) {
  this.router.navigate(['']);
}

因此,在您确定auth是否有效后,您需要在订阅中运行该代码。我不确定为什么你的令牌不会返回。我会看一下网络选项卡/服务器调试器来解决这个问题。