Angular canActivate从服务获取更新的变量

问题描述

我有一个来自服务的发布请求,如果用户登录,该请求将返回,我想将authGuard设置为仅在用户登录显示管理面板。 我的发帖要求如下:

import { Link } from "react-router-dom";

<Nav.Link
  as={Link} // --> render as react-router-dom Link
  to="/news"
  name="news"
  active={active === "/news"}
  onClick={() => setActive("/news")}
>
  News
</Nav.Link>

我的authguard具有以下内容

public isLoggedIn: boolean = false;
checkSesh(data: object) {
    const options = {
      headers: new HttpHeaders().set('Content-Type','application/json; charset=utf-8'),withCredentials: true
    }

    return this.http.post<any>(`${this.AUTH_SERVER}`,data,options).subscribe(
      (res) => {
        this.reload = res[0].reload;
        if (this.reload === 0) {
          this.isLoggedIn = true;
        }
      }
    );
  }

但是它返回false(在订阅之前获取布尔值)。

发布请求运行且值已更新后,如何更新?

谢谢

解决方法

您需要在canActivate函数中返回Observable。 因此,您可以将结果映射到checkSesh函数中,以返回true / false。 像这样:

EXPLAIN ANALYZE
with TempResult AS (
    select DISTINCT lead.id AS lead_id,last_activity_join.last_activity,lead_last_response_time.last_response_time
    from lead
             left join (select * from last_activity_with_client where client_id = 13189) last_activity_join on
        lead.id = last_activity_join.lead_id

             left join lead_last_response_time lead_last_response_time on
        lead.id = lead_last_response_time.lead_id

             join date_dimensions date_dimensions on
        lead.insert_date = date_dimensions.key

    where (date_dimensions.past_30 = true)
      and (lead.client_id in (13189))
),TempCount AS (
         select COUNT(*) as total_rows
         fromt TempResult
     )
select *
from TempResult,TempCount
order by last_response_time desc NULLS LAST
limit 25 offset 1;

然后在canActivate函数中,您可以执行以下操作:

checkSesh(data: object) {
    const options = {
        headers: new HttpHeaders().set('Content-Type','application/json; charset=utf-8'),withCredentials: true
    }

    return this.http.post<any>(`${this.AUTH_SERVER}`,data,options)
        .pipe(
            map((res) => {
                this.reload = res[0].reload;
                if (this.reload === 0) {
                    this.isLoggedIn = true;
                    return true;
                }
                return false;
            })
        );
}