基于 Observable 的 paramMap 方法的用例
Use case of Observable based paramMap approach
我通常在 routes 上用我的应用程序使用这种方式。
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.hero$ = this.service.getHero(id);
}
但是在文档上方我也可以看到基于 Observable 的方法。
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
你能告诉我为什么我们需要这种方法吗?医生说
you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component.
不过我不是很清楚。你能告诉我为什么我们需要基于 Observable 的方法吗?
这意味着您的方式将仅获得参数的第一个值。但是,如果您需要处理参数更改(例如存储在查询字符串中的过滤器更改),则需要使用第二种方法
you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component.
这意味着如果同一组件有导航事件,Angular 将不会重新创建该组件,因为它已经可用。因此 ngOnInit 不会再 运行 ,导致忽略参数的变化(快照只保存第一个出现的值)。在可观察方法的情况下,它将被订阅并处理参数的变化。
当您显示产品之类的实体并且有相关产品的导航按钮时,应考虑此用例。
假设 url 是 "DOMAIN/product/1" 并且产品 2 有 link。通过单击 link,浏览器将 url 更改为 "DOMAIN/product/2" 但 angular 将重用产品展示组件。由于上述原因,快照方法将不会注意到变化。
你需要一个 observable 因为如果你有一条路线 "user/2" 并且你有这个 aprroach
this.id = this.route.snapshot.paramMap.get('id');
当您在 url 中将 2 更改为 3 时,您在 this.id
中的值保持为“2”,如果您有此方法:
> this.id$ = this.route.paramMap.pipe(
> map((params: ParamMap) => params.get('id')),
> );
你的新用户有一个可观察的 "id" 因为当你使用不同的参数重新导航到同一条路线时 angular 不要破坏并重新创建组件所以当你改变你的时 ngOnInit 不会再次触发参数。
我通常在 routes 上用我的应用程序使用这种方式。
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.hero$ = this.service.getHero(id);
}
但是在文档上方我也可以看到基于 Observable 的方法。
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
你能告诉我为什么我们需要这种方法吗?医生说
you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component.
不过我不是很清楚。你能告诉我为什么我们需要基于 Observable 的方法吗?
这意味着您的方式将仅获得参数的第一个值。但是,如果您需要处理参数更改(例如存储在查询字符串中的过滤器更改),则需要使用第二种方法
you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component.
这意味着如果同一组件有导航事件,Angular 将不会重新创建该组件,因为它已经可用。因此 ngOnInit 不会再 运行 ,导致忽略参数的变化(快照只保存第一个出现的值)。在可观察方法的情况下,它将被订阅并处理参数的变化。
当您显示产品之类的实体并且有相关产品的导航按钮时,应考虑此用例。
假设 url 是 "DOMAIN/product/1" 并且产品 2 有 link。通过单击 link,浏览器将 url 更改为 "DOMAIN/product/2" 但 angular 将重用产品展示组件。由于上述原因,快照方法将不会注意到变化。
你需要一个 observable 因为如果你有一条路线 "user/2" 并且你有这个 aprroach
this.id = this.route.snapshot.paramMap.get('id');
当您在 url 中将 2 更改为 3 时,您在 this.id
中的值保持为“2”,如果您有此方法:
> this.id$ = this.route.paramMap.pipe(
> map((params: ParamMap) => params.get('id')),
> );
你的新用户有一个可观察的 "id" 因为当你使用不同的参数重新导航到同一条路线时 angular 不要破坏并重新创建组件所以当你改变你的时 ngOnInit 不会再次触发参数。