【问题标题】:Can not get params['id'] from routing in a service [duplicate]无法从服务中的路由中获取参数 ['id'] [重复]
【发布时间】:2020-01-25 07:05:59
【问题描述】:

想象以下路线:

// student-info/120
{
  path: "student-info/:id", component: StudentInfoComponent
}

如果我想获取组件中的id,那就对了

constructor(private route: ActivatedRoute) { }
ngOnInit() {
  alert(this.route.snapshot.params['id']);
}

如果我想在服务中获取 id,它会返回 undefined ...

@Injectable({
  providedIn: 'root'
})
export class StudentService {

  constructor(private route: ActivatedRoute) { }

  getParams() {
    return this.route.snapshot.params['id'];
  }
}

Demo:(点击按钮查看)

【问题讨论】:

  • 请在组件元数据中使用StudentService:提供者:[StudentService]

标签: angular angular-routing


【解决方案1】:

尝试用这种方式获取id

constructor(private route: ActivatedRoute){
  let id = JSON.parse(this.route.snapshot.paramMap.get('id'));
}

【讨论】:

  • 它返回 null
  • 我觉得从当前组件的 ActivatedRoute 和服务获取参数的值是有区别的。
  • 这是你的权利,因为如果我得到组件中的 prams['id'],它就可以正常工作
  • 不确定从非路由组件/服务访问是否是一个好习惯。
猜你喜欢
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 2019-02-12
  • 2016-12-28
相关资源
最近更新 更多