所以我的路线决心如下。它只是解析用户json。
const routes: Routes = [
{ path: 'profile/:id', component: ProfileEditComponent, pathMatch: 'full',
canActivate: [AuthGuard],
resolve: {
user: ProfileResolveService
}
},
];
My Resolve服务是:
@Injectable()
export class ProfileResolveService implements Resolve<any> {
constructor(private service: UserService, private router: Router,
private notificationService: NotificationService) {}
resolve(route: ActivatedRouteSnapshot) {
const id = route.paramMap.get('id');
return this.service.getUserProfile(id).map((response) => {
return response;
}).subscribe(user => user, (error) => {
this.router.navigate(['/login']);
this.notificationService.error('Oops! Something went wrong.', 3000);
return null;
});
}
}
我试图在组件中获得解析并执行以下操作:
this.activatedRoute.data.map(data => {
return data.user;
}).subscribe((res) => {
console.log('res', res);
});
但是,我没有得到价值,而是在日志中得到{user: Subscriber}
答案 0 :(得分:0)
这是因为你要在
中返回整个用户对象 return data.user;
如果您想要用户值,可以使用
console.log('res', res.user); or res['user']
它将打印用户值
答案 1 :(得分:0)
你可以尝试下面那样
resolve(route: ActivatedRouteSnapshot) {
const id = route.paramMap.get('id') || '';
return this.service.getUserProfile(id)
.map((response: any) => {
return response.data;
}).catch(Error => {
this.notificationService.error('Oops! Something went wrong.', 3000);
this.router.navigate(['/login']);
return null;
});
}
您组件中的
var user = this.aroute.snapshot.data['user'];
答案 2 :(得分:0)
您可以在处理错误时尝试此操作
resolve(route: ActivatedRouteSnapshot) {
const id = route.paramMap.get('id') || '';
return this.service.getUserProfile(id).catch((err) =>{
this.router.navigate(['/login']);
return Observable.of(null);
});
}
在组件中这样做
this.activatedRoute.data.subscribe((res) => {
console.log('user', res.user);
});