【发布时间】:2018-09-03 10:58:21
【问题描述】:
有网址说:
学生/学生资料/:id
我不希望用户直接访问此网址。相反,如果他们尝试直接加载它,我想导航到“学生/我的学生”。
为了实现这一点,我创建了一个名为 previousRouteService 的服务:
import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
@Injectable()
export class PreviousRouteService {
private previousUrl: string = undefined;
private currentUrl: string = undefined;
constructor(private router : Router) {
this.currentUrl = this.router.url;
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
};
});
}
public getPreviousUrl(){
return this.previousUrl;
}
canNavigateToProfile()
{
console.log('this.previousUrl', this.previousUrl)
if(this.previousUrl === 'students/my-students')
{
return true
}
else
{
this.router.navigate(['students/my-students']);
return false;
}
}
}
然后在 src/app/gaurds/post-login/student-profile/student-profile.gaurd.ts 中创建了一个 gaurd:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { PreviousRouteService } from '@app/services';
@Injectable()
export class StudentProfile implements CanActivate {
constructor(private previousRoute: PreviousRouteService
) { }
canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.previousRoute.canNavigateToProfile();
}
}
在延迟加载的模块文件中:
path: 'student-profile/:id',
canActivate: [StudentProfile],
loadChildren: 'app/views/student-post-login/student-profile/student-profile.module#PatientProfileModule'
@NgModule({
imports: [
......
......
providers: [studentProfile]
})
但是当我尝试通过 my-students 路由导航到 student-profile/:id 路由时:
core.js:1448 ERROR 错误:未捕获(承诺):错误: StaticInjectorError(AppModule)[studentProfile -> PreviousRouteService]:StaticInjectorError(平台: 核心)[studentProfile -> PreviousRouteService]: NullInjectorError:没有PreviousRouteService 的提供者!错误:StaticInjectorError(AppModule)[studentProfile -> PreviousRouteService]:StaticInjectorError(平台: 核心)[studentProfile -> PreviousRouteService]: NullInjectorError:没有PreviousRouteService 的提供者!
如果我从患者资料 gaurd 中删除 previousRouteService 的使用,那么这个错误就会消失。
此错误的原因可能是什么以及实现这种限制的最佳方法是什么,用户可以通过 url xyz 导航到 url abc 否则应该导航到 xyz。
【问题讨论】: