【发布时间】: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