Angular2 auth guard通过observable跟踪当前用户

时间:2017-07-06 04:04:42

标签: angular authentication angular2-services

我对Angular和 我试图在我的应用程序中编写一个auth guard, 我知道我每次都可以点击我的服务器并获取有关登录用户的会话信息。 但我想在整个应用程序中跟踪登录用户...

app.component.ts

<style>
div{
  display:inline-block;
  float:left;
  color:#fff;
  font-size:20px;
}

.one{
  width:100px;
  height:100px;
  background:red;
  clear:both;
}
.three{
    width:100px;
  height:100px;
}

.four{
  width:150px;
  height:50px;
background:darkblue;
}
.five{
  width:150px;
  height:50px;
background:blue;
}
 </style>

<div class="one">image</div>

<div class="three">
  <div class="four">name</div>
  <div class="five">desc</div>
</div>

<div class="one">image</div>

<div class="three">
  <div class="four">name</div>
  <div class="five">desc</div>
</div>

<div class="one">image</div>

<div class="three">
  <div class="four">name</div>
  <div class="five">desc</div>
</div>

AuthenticationService.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});
  }
}

AUTH-guard.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);
        })
    }
}

login.component.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)
  }
}

auth-guard总是在这里返回false,我不知道为什么。 认证服务是否在auth-guard中定义并登录不同的实体?

2 个答案:

答案 0 :(得分:0)

total_iterations = tf.constant((LENGTH_MAX_OUTPUT + 1) * (LENGTH_MAX_OUTPUT+1) * BATCH_SIZE)
iteration2 = tf.Variable(0, trainable=False)
cost = tf.constant(0, dtype=tf.float32)
cost_cum = tf.Variable(0, dtype=tf.float32, trainable=False)
cost_matrix = tf.Variable(np.ones(((LENGTH_MAX_OUTPUT+1) , (LENGTH_MAX_OUTPUT+1))), dtype=tf.float32, trainable=False)
batch_size = tf.constant(BATCH_SIZE, dtype=tf.float32)

it_batch_continue = lambda cost: tf.less(iteration2, total_iterations)

def get_value(it_row_nr, it_col_nr, it_batch_nr):
    abs_diff = tf.abs(tf.subtract(decoder_targets[it_row_nr, it_batch_nr], decoder_predictions[it_col_nr, it_batch_nr]))

    prev_row = cost_matrix[tf.subtract(it_row_nr, 1), it_col_nr]
    prev_col = cost_matrix[it_row_nr, tf.subtract(it_col_nr, 1)]
    prev_rowcol = cost_matrix[tf.subtract(it_row_nr, 1), tf.subtract(it_col_nr, 1)]

    min_prev_row_col_rowcol = tf.minimum(tf.minimum(prev_col, prev_row), prev_rowcol)

    z_z_condition = tf.logical_and(tf.less(it_row_nr, 1), tf.less(it_col_nr, 1))
    z_z_true = lambda: abs_diff
    z_z = tf.cond(z_z_condition, z_z_true, lambda: tf.constant(99999, dtype=tf.float32))

    n_z_condition = tf.logical_and(tf.greater(it_row_nr, 0), tf.equal(it_col_nr, 0))
    n_z_true = lambda:  prev_row + abs_diff
    n_z = tf.cond(n_z_condition, n_z_true, lambda: z_z)

    z_n_condition = tf.logical_and(tf.equal(it_row_nr, 0), tf.greater(it_col_nr, 0))
    z_n_true = lambda: prev_col + abs_diff
    z_n = tf.cond(z_n_condition, z_n_true, lambda: n_z)

    n_n_condition = tf.logical_and(tf.greater(it_row_nr, 0), tf.greater(it_col_nr, 0))
    n_n_true = lambda: min_prev_row_col_rowcol + abs_diff
    n_n = tf.cond(n_n_condition, n_n_true, lambda: z_n)
    return(n_n) # Note that the False method calls one of the other methods

def iterate_batch(cost):
    row_nr = iteration2 % (LENGTH_MAX_OUTPUT + 1)
    col_nr = (iteration2 - row_nr) / (LENGTH_MAX_OUTPUT + 1) % (LENGTH_MAX_OUTPUT + 1)
    batch_nr = (iteration2 - col_nr * (LENGTH_MAX_OUTPUT + 1) - row_nr) / ((LENGTH_MAX_OUTPUT + 1) *  (LENGTH_MAX_OUTPUT + 1))

    val = get_value(row_nr, col_nr, batch_nr)   
    update_cost_matrix = tf.assign(cost_matrix[row_nr,col_nr], val)

    with tf.control_dependencies([update_cost_matrix]):
        update_cost_cum = tf.assign_add(cost_cum, tf.cond(tf.logical_and(tf.equal(row_nr, LENGTH_MAX_OUTPUT), tf.equal(col_nr, LENGTH_MAX_OUTPUT)), lambda: cost_matrix[-1,-1], lambda: tf.constant(0.0)))
        with tf.control_dependencies([update_cost_cum]):
            cost = cost_cum / (batch_size+1.0)
            update_iteration = tf.assign_add(iteration2,1)
            with tf.control_dependencies([update_iteration]):
                return tf.add(cost,0)

loss = tf.while_loop(it_batch_continue, iterate_batch, [cost])
train_op = tf.train.AdamOptimizer().minimize(loss)

始终返回第一个值。

  

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

将其更改为

return this.authService.isAuthenticated.take(1)

答案 1 :(得分:0)

这可能是因为您从一个空的(或刚刚初始化的)主题创建了可观察对象。当您实例化该值时,可以观察到的就是将其值带入主题一次。 如果要将其用作Observable,请通过方法或getter实例化它。

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