dop*_*man 22 angular2-routing angular
我是Angular2的新手,我已经习惯了Angular 1摘要周期,这意味着如果我更新视图的范围,我可以通过调用手动触发摘要$scope.$digest().但是,我不确定如何在Angular2中执行此操作,因为新框架没有旧版本具有的隐式数据绑定.
这是我的问题.我有一个路由,当一个带有参数的网址被命中时加载一个组件:
// Router
export const AppRoutes : RouterConfig = [
{
path: 'my/:arg/view',
component: MyComponent
}
]
Run Code Online (Sandbox Code Playgroud)
然后我有这个组件:
// Component
export class MyComponent {
constructor(private route : ActivatedRoute,
private r : Router) {
let id = parseInt(this.route.params['value'].id);
console.log(id);
// do stuff with id
}
reloadWithNewId(id:number) {
this.r.navigateByUrl('my/' + id + '/view');
}
}
Run Code Online (Sandbox Code Playgroud)
让我们说我导航到网址/my/1/view.它将调用构造函数并1记录数字.但是,如果我reloadWithNewId使用新的id 调用,reloadWithNewIf(2)则不会再次调用构造函数.如何手动重新加载组件?
Gün*_*uer 16
不需要重新加载组件.只需更新模型,视图就会自动更新:
export class MyComponent {
constructor(private route : ActivatedRoute,
private r : Router) {}
reloadWithNewId(id:number) {
this.r.navigateByUrl('my/' + id + '/view');
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.paramsChanged(params['id']);
});
}
paramsChanged(id) {
console.log(id);
// do stuff with id
}
}
Run Code Online (Sandbox Code Playgroud)
小智 13
您可以通过导航到其他URL然后返回到所需的URL来强制angular2重新初始化组件.
以下是使用Router类方法的简单解决方法(参考:https://angular.io/docs/ts/latest/api/router/index/Router-class.html)
组件构造函数:
constructor(private router: Router) {}
Run Code Online (Sandbox Code Playgroud)
在模板(示例)中:
(click)="onTabChange(id)"
Run Code Online (Sandbox Code Playgroud)
然后在组件类中:
onTabChange() {
if (this.router.navigated === false) {
// Case when route was not used yet
this.router.navigateByUrl(`/module/${id}`);
} else {
// Case when route was used once or more
this.router.navigateByUrl(`/index`).then(
() => {
this.router.navigateByUrl(`/module/${id}`);
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62888 次 |
| 最近记录: |