【问题标题】:Why won't guard allow the router to activate after HTTP request?为什么守卫在HTTP请求后不允许路由器激活?
【发布时间】:2020-01-09 23:57:25
【问题描述】:

我有一个守卫,它要么返回 Observable,要么根据 HTTP 响应路由到另一个 url。守卫正在调用的服务将进行 HTTP 调用,或者如果它已经被调用并保存在服务中,它应该返回存储的值。请参阅下面的服务。如果没有 if 语句,一切正常,但如果使用 if 语句,守卫似乎不允许路由器激活(地图返回 true)。控制台没有错误。提前致谢。

编辑:使用 Angular 8.1

服务:

private company: Company;
public companySubject: BehaviorSubject<Company> = new BehaviorSubject(this.company);

get(slug: string, params: HttpParams = null): Observable<Company>
  {
    if (this.company && this.company.slug === slug) {
      this.companySubject.next(this.company);
      return this.companySubject.asObservable();
    }

    return this.http.get<Company>(`companies/${slug}`, {params: params}).pipe(
      tap((response: Company) => {
        this.company = response;
        this.companySubject.next(this.company);
      })
    );
  }

后卫:

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>
  {
    const slug = route.parent.paramMap.get('company');

    return this.companyService.get(slug).pipe(
      tap((company: Company) => {
        if (
          company.locations_count == 0 ||
          !company.subscribed
        ) {
          this.router.navigateByUrl(`/app/company/${slug}/setup`);
        }
      }),
      map(() => true)
    );
  }

【问题讨论】:

  • 您好,您使用的是哪个 Angular 版本?
  • @Soukyone Angular 8.1

标签: angular angular8


【解决方案1】:

我认为你可以用更简单的方式做到这一点:

private company: Company;

get(slug: string, params: HttpParams = null): Observable<Company>
{
  if (this.company && this.company.slug === slug) {
    return of(this.company);
  }

   return this.http.get<Company>(`companies/${slug}`, {params: params}).pipe(
      tap((response: Company) => {
        this.company = response;
       }),
       map(res => res)
  );
}

【讨论】:

  • 谢谢!是的,似乎返回 this.companySubject.asObservable();是什么打破了它。将其更改为 return of(this.company);让它工作。
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 2012-07-07
相关资源
最近更新 更多