我在使用 Angular 2 路由时遇到了一个非常奇怪的问题,我ngOnInit
在路由到的组件中被调用了两次,并且浏览器中的路由被重置为原始路由。
我有一个NotificationListComponent
和NotificationEditComponent
一个MaintenanceModule
。
在我的根目录AppModule
中,我设置RouterModule
将任何未映射的路由重定向到/maintenance/list
.
app.module.ts:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
RouterModule.forRoot([
{path: "", redirectTo: "maintenance/list", pathMatch: "full"},
{path: "**", redirectTo: "maintenance/list", pathMatch: "full"}
], {useHash: true}),
CoreModule.forRoot({notificationUrl: "http://localhost:8080/notification-service/notifications"}),
MaintenanceModule
],
providers: [NotificationService],
bootstrap: [AppComponent]
})
export class AppModule { }
我/maintenance/list
在 my 中定义了MaintenanceModule
指向 myNotificationListComponent
的路线,以及/maintenance/edit/:id
指向 my 的路线NotificationEditComponent
。
维护.module.ts:
@NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{path: "maintenance/list", component: NotificationListComponent, pathMatch: 'full'},
{path: "maintenance/edit/:id", component: NotificationEditComponent, pathMatch: 'full'}
]),
FormsModule
],
declarations: [
NotificationListComponent,
NotificationEditComponent
]
})
export class MaintenanceModule {}
当我的应用程序加载时,它会正确地遵循/maintenance/list
路线,并且我可以在列表中看到我的所有通知。对于列表中的每个通知,都有一个编辑图标,它的click
事件绑定到edit(id: number)
我的方法NotificationListComponent
通知列表.component.ts:
@Component({
templateUrl: 'notification-list.component.html'
})
export class NotificationListComponent implements OnInit {
notifications: Notification[];
errorMessage: string;
constructor(private _notificationService: NotificationService,
private _router: Router) {}
ngOnInit(): void {
this._notificationService.getNotifications()
.subscribe(
notifications => this.notifications = notifications,
error => this.errorMessage = <any>error);
}
clearError(): void {
this.errorMessage = null;
}
}
通知列表.component.html:
<div class="row">
<h1>Notification Maintenance</h1>
<div *ngIf="errorMessage" class="alert-box alert">
<span>{{errorMessage}}</span>
<a class="right" (click)="clearError()">×</a>
</div>
<p-dataTable [value]="notifications" [sortField]="'code'" [responsive]="true" [sortOrder]="1" [rows]="10" [paginator]="true" [rowsPerPageOptions]="[10,50,100]">
<p-header>Available Notifications</p-header>
<p-column [field]="'code'" [header]="'Code'" [sortable]="true" [style]="{'width':'10%'}"></p-column>
<p-column [field]="'name'" [header]="'Name'" [sortable]="true" [style]="{'width':'40%'}"></p-column>
<p-column [field]="'roles'" [header]="'Roles'" [style]="{'width':'40%'}"></p-column>
<p-column [field]="'notificationId'" [header]="'Edit'" [style]="{'width':'10%'}">
<template let-row="rowData" pTemplate="body">
<a [routerLink]="'/maintenance/edit/' + row['notificationId']"><span class="fa fa-pencil fa-2x"></span></a>
</template>
</p-column>
</p-dataTable>
</div>
如您所见,该edit(id: number)
方法应导航到该/maintenance/edit/:id
路线。当我单击图标导航到该路线时,浏览器会在地址栏中闪烁正确的路线(例如localhost:4200/#/maintenance/edit/2
),但随后地址栏中的路线立即变回localhost:4200/#/maintenance/list
。即使/maintenance/list
地址栏中返回的路由,我NotificationEditComponent
在实际应用中仍然可见。但是,我可以看到该ngOnInit
方法在 my 中被调用了两次NotificationEditComponent
,因为两次id
被记录到控制台,如果我在ngOnInit
函数中放置一个断点,它会两次命中该断点。
通知-edit.component.ts:
@Component({
templateUrl: "notification-edit.component.html"
})
export class NotificationEditComponent implements OnInit{
notification: Notification;
errorMessage: string;
constructor(private _notificationService: NotificationService,
private _route: ActivatedRoute,
private _router: Router) {
}
ngOnInit(): void {
let id = +this._route.snapshot.params['id'];
console.log(id);
this._notificationService.getNotification(id)
.subscribe(
notification => this.notification = notification,
error => this.errorMessage = <any>error
);
}
}
这似乎也导致了其他问题,因为当尝试将input
值绑定到我NotificationEditComponent
使用的值时,例如[(ngModel)]="notification.notificationId"
,该值没有显示在屏幕上,即使我可以看到 Augury chrome 扩展,以及记录对象到控制台,该值已填充到组件中。
通知-edit.component.html:
<div class="row">
<h1>Notification Maintenance</h1>
<div *ngIf="errorMessage" class="alert-box alert">
<span>{{errorMessage}}</span>
<a class="right" (click)="clearError()">×</a>
</div>
<p-fieldset [legend]="'Edit Notification'">
<label for="notificationId">ID:
<input id="notificationId" type="number" disabled [(ngModel)]="notification.notificationId"/>
</label>
</p-fieldset>
</div>
有谁知道为什么会这样?
更新:
我删除了对 的调用NotificationService
,并用一些模拟数据替换它们,然后路由开始工作!但是,一旦我向我的服务添加调用,我就会遇到上面描述的相同问题。我什至删除了CoreModule
并将服务直接添加到我的MaintenanceModule
中,但每当我使用实际服务而不是模拟数据时,仍然会遇到同样的问题。
notification.service.ts:
@Injectable()
export class NotificationService {
private _notificationUrl : string = environment.servicePath;
constructor(private _http: Http) {
}
getNotifications(): Observable<Notification[]> {
return this._http.get(this._notificationUrl)
.map((response: Response) => <Notification[]>response.json())
.catch(this.handleGetError);
}
getNotification(id: number): Observable<Notification> {
return this._http.get(this._notificationUrl + "/" + id)
.map((response: Response) => <Notification>response.json())
.catch(this.handleGetError);
}
postNotification(notification: Notification): Observable<number> {
let id = notification.notificationId;
let requestUrl = this._notificationUrl + (id ? "/" + id : "");
return this._http.post(requestUrl, notification)
.map((response: Response) => <number>response.json())
.catch(this.handlePostError);
}
private handleGetError(error: Response) {
console.error(error);
return Observable.throw('Error retrieving existing notification(s)!');
}
private handlePostError(error: Response) {
console.error(error);
return Observable.throw('Error while attempting to save notification!');
}
}
NotificationEditComponent
而且服务似乎运行良好 - 我可以看到端点成功返回数据,并且当我使用 Augury chrome 扩展程序查看我的数据时,我可以看到数据看起来正确。但是数据没有显示在模板中,/maintenance/list
即使/maintenance/edit/:id
仍然显示路由的模板,URL 中的路由也会返回。
更新 2:
正如@user3249448 所建议的,我将以下内容添加到我AppComponent
的调试中:
constructor(private _router: Router) {
this._router.events.pairwise().subscribe((event) => {
console.log(event);
});
}
这是我单击“编辑”链接之一时的输出: