PS:
当我和我的同事交谈时,他们告诉我一次请求就可以让角色正确,如果它没有经过身份验证则拒绝,否则将数据返回到前端。但是,我被困在使用 Angular2 的 Guard 中。
应用程序可以:
- 访问我的路由并
Guard
阻止它,Guard 向服务器发送请求以检查其身份验证。 server
当服务器返回时请求statue:true
,data:[somedatas]
然后使用模块的 dataService 设置数据,并解析true
为 canActivate。- 初始化目标组件, in
constructor
,用于dataService
获取元数据。
但是,我未能将数据从我的 Guard 传递给 Service。我在同一个模块中提供它们。这是我的代码:
模块.ts:
@NgModule({
declarations: [
DocsComponent,
DocsListComponent, // this is the component I will access
BarButtonsComponent
],
imports: [
CommonModule,
DocsRouting,
// ShareModule
],
providers:[
DocsGuard,
DocsDataService // here I provide my dataService that I mentioned before
],
exports: [DocsComponent],
})
路线:
const DOCS_ROUTES:Routes = [
{path:'',redirectTo:'doclist',pathMatch:'full'},
{path:'',component:DocsComponent,children:[
{path:'doclist', component: DocsListComponent}
], canActivate:[DocsGuard] } // use `Guard` to prevent it.
];
我的数据服务.ts:
private doclist:Doclist[] ; // this
getData(){
return this.doclist;
}
setData(obj){
this.doclist = obj;
}
getDocAuth(): Observable<any>{
let options = new RequestOptions({
withCredentials:true
});
// ...using get request
return this.http.get(this.docUrl,options)
// ...and calling .json() on the response to return data
.map((res:Response) =>res.json())
//...errors if any
.catch((error:any) => {
console.log(error)
})
}
Guard.ts:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean>{
let subject = new Subject<boolean>();
let that = this;
this.docsDataService.getDocAuth().subscribe(
res=>{
if(res.status){
// Here I want to pass data to my component, I failed.
that.docsDataService.setData(res.data);
subject.next(true);
}else{
subject.next(false);
}
console.log("next: returning true");
},
err => {
console.log(err);
subject.next(false);
}
);
return subject.asObservable().first();
}
谢谢。
======================补充2017-02-17 17:34=================== ===
应用模块路线:
const APP_ROUTERS:Routes = [
{ path:'',component:JwLoginComponent},
{ path:'main',loadChildren:'app/main/main.module#MainModule'},
{ path:'**', component: PageNotFoundComponent }
];
主要路线:
const MAIN_ROUTES : Routes = [
{path:'main',component:MainComponent,canActivate:[DataGuard]},
{path:'share',loadChildren:'app/common/share.module#ShareModule'}
];
分享路线:
const SHARE_ROUTES:Routes = [
{path:'',redirectTo:'docs',pathMatch:'full'},
{path:'',component: ShareComponent,children:[
{ path:'docs',loadChildren:'app/docs/docs.module#DocsModule'},
// Question here: cannot get data from service set in DocsModule, but in MainModule or AppModule as providers.
{ path:'mic',loadChildren:'app/mic/mic.module#MicModule'},
{ path:'user-manage',loadChildren:'app/user-manage/user-manage.module#UserManageModule'},
{ path:'settings',loadChildren:'app/settings/settings.module#SettingsModule'},
{ path:'logs',loadChildren:'app/logs/logs.module#LogsModule'}
]},
];
我发现我DocService
在 MainModule 或 AppModule 中提供了,我可以从 @mxii 代码中获取数据。但是,当我将此服务设置为 DocsModule 或 ShareModule 时,我无法获取数据。