You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何获取Angular路由Resolve解析的数据?

获取Angular Resolve解析后的数据的方法

哈哈,这个问题我熟!你已经把Resolve配置好了,接下来在ProfileEditComponent里有两种简单的方式能拿到解析后的用户数据,我给你分别说下:

方法一:订阅ActivatedRoute的data Observable

这种方式适合组件可能复用、路由参数会变化的场景(比如从profile/1跳转到profile/2,同一个组件不需要重新初始化,但要获取新的用户数据):

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-profile-edit',
  templateUrl: './profile-edit.component.html',
  styleUrls: ['./profile-edit.component.css']
})
export class ProfileEditComponent implements OnInit {
  user: any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    // 订阅data的变化,每次路由参数更新后都会触发
    this.route.data.subscribe((resolvedData) => {
      this.user = resolvedData.user;
      // 拿到数据后就可以做你需要的操作啦,比如填充表单、渲染用户信息
    });
  }
}

方法二:直接从ActivatedRoute快照获取数据

如果你的组件初始化后不会因为路由参数变化而复用,直接用快照获取会更简单:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-profile-edit',
  templateUrl: './profile-edit.component.html',
  styleUrls: ['./profile-edit.component.css']
})
export class ProfileEditComponent implements OnInit {
  user: any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    // 从路由快照里直接取数据,仅在组件初始化时生效
    this.user = this.route.snapshot.data['user'];
  }
}

关键注意点

这里的user键要和你路由配置里resolve: { user: ProfileResolveService }的key完全一致哦!如果你把路由里的key改成profileUser,那代码里就要用resolvedData.profileUser或者snapshot.data['profileUser']来获取。

内容的提问来源于stack exchange,提问作者JyotiChhetri

火山引擎 最新活动