在angular2 routerLink中,我使用[routerLink] =“['XXXX',function()]”,但在partComponent中该函数两次工作
app.component.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DetailComponent } from './detail/detail.component';
import { ListComponent } from './list/list.component';
const routes: Routes = [
{ path: 'detail/:id', component: DetailComponent},
{ path: 'list', component: ListComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
detail.component.html
<a [routerLink]="['/detail', nextInfo()]">
下一个联系人
</a>
detail.components.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Route, Router } from '@angular/router';
import { ListComponent } from '../list/list.component';
@Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit, OnDestroy {
contact_id: string;
private sub: any;
numd = 1;
constructor( private _activatedRoute: ActivatedRoute, private _router: Router) {
console.log('创建DeatilComponent组件实例');
}
ngOnInit() {
this.sub = this._activatedRoute.params.subscribe(params => {
this.contact_id = params['id'];
console.log('参数id为:' + this.contact_id);
});
}
nextInfo() {
console.log(this.numd);
// this.numd++;
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
为什么这个nextInfo()两次在detail.component.ts中工作。我不知道为什么,因为它是angular2中的一个错误
对此的解决方法是在(click)
中使用nextInfo()而不是直接在routerLink
中使用:
变化:
// nextInfo will be invoked by itself on each time view refreshed
<a [routerLink]="['/detail', nextInfo()]">
下一个联系人
</a>
至 :
<a [routeLink]=['/detail', numd] (click)="nextInfo()">
下一个联系人
</a>
原因是
changeDetection
循环,在你的情况下你的函数会在每次对数据进行任何更改时被调用并反映到模板端,为了防止这种情况应该在特定事件上被触发,在你的情况下它的点击。
有关更多详细信息,请阅读:LifeCycleHooks
这将有助于您调试以及了解流程的方式。
它工作两次的原因是你处于开发模式。变化检测每次触发两次。在模板中调用函数不是一个好习惯,因为每次检测到更改时都会调用它们。
如果启用prod模式,它将不会触发两次。但是,我仍然会重新考虑在模板中调用一个函数。