angular - 如何获取路由数据解析值?

标签 angular angular4-router

所以我的路线如下。它只是解析用户 json。

const routes: Routes = [
  { path: 'profile/:id', component: ProfileEditComponent, pathMatch: 'full',
    canActivate: [AuthGuard],
    resolve: {
      user: ProfileResolveService
    }
  },
];

我的解决服务是:

@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}

最佳答案

你可以像下面这样尝试

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'];

关于angular - 如何获取路由数据解析值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49994367/

相关文章:

angular - 从Electron Angular项目运行Karma时出错

angular - 无法绑定(bind)到 'routerLink',因为它不是 'a' 的已知属性。尽管引用了路由器模块,但还是有错误

javascript - 在 Angular 中路由时使用 `%` 时,URL `%25` 会被 `queryParams` 替换

angular - $locationChangeStart 等同于 Angular 4

Angular 4未加载组件

angular - PWA 离线授权

angular - 只运行一次订阅

angular - 为什么我在刚启动的 Angular2 应用程序中会收到此错误?

angular - ActivatedRoute .parent 在 Angular 4 中是一个空对象

BehaviourSubject 的 Angular 订阅者多次触发