gpt4 book ai didi

没有在每个路由请求上调用 Angular 4 Component ngOnInit

转载 作者:太空狗 更新时间:2023-10-29 17:20:51 25 4
gpt4 key购买 nike

我最近才开始深入研究来自 Angular 1.5 的 Angular 4。我正在处理用户路由并将 API 数据从服务提取到用户组件中。

组件似乎保持静态,不像 1.* 中的 Controller ,它们在每次请求时刷新。

是否有在每个新路由请求上调用 ngOnInit 函数的方法?

我的用户组件类:

// url structure: /user/:id
export class UserComponent implements OnInit {

constructor(private route: ActivatedRoute) {}

ngOnInit() {

// doesn't log new id on route change
let id = this.route.snapshot.params['id'];
console.log(id);

this.route.params
.switchMap(params => this.userService.getUser(params['id']))
.subscribe(user => {
// logs new id on route change
let id = this.route.snapshot.params['id'];
console.log(id);

this.user = user
});
}
}

更新:

找到了一个我认为最适合我的场景的解决方案。根据对我的问题的几个答案和评论以及进一步的调查,订阅路线似乎是可行的方法。这是我更新的组件:

export class UserComponent {

user;
id;

constructor(
private userService: UserService,
private route: ActivatedRoute
) {}


ngOnInit() {
this.route.params
.subscribe(params => this.handleRouteChange(params));
}

handleRouteChange(params) {
this.id = params['id'];

switch (this.id) {
case '1':
console.log('User 1');
break;

case '2':
console.log('User 2');
break;

case '3':
console.log('User 3');
break;
}

this.userService.getUser(this.id).
subscribe(user => this.user = user);
}

}

最佳答案

如果路由相同但参数发生变化,Angular 更喜欢 - 默认情况下 - 重用相同的组件而不是实例化一个新组件。

好消息!这是一个可定制的行为,您可以通过实现自己的 RouteReuseStrategy 来强制实例化一个新的组件实例。 :

export class MyRouteReuseStrategy extends DefaultRouteReuseStrategy {
shouldReuseRoute(next: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
let name = next.component && (next.component as any).name;
return super.shouldReuseRoute(next, current) && name !== 'UserComponent';
}
}

在你的模块中:

@NgModule({
...
providers:[{
provide: RouteReuseStrategy,
useClass: MyRouteReuseStrategy}]
...
})
export class AppModule {}

(此代码或多或少来自 this article ,尤其是对 name 属性的检查可能不是很准确...)

请注意,重新实例化同一组件时可能会出现一些性能缺陷。因此,也许您最好使用 observables 属性而不是快照。

关于没有在每个路由请求上调用 Angular 4 Component ngOnInit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43806492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com