2017-03-09 62 views
11

Yönlendirdiğim bileşendeki ngOnInit adresimin iki kez çağrıldığını ve tarayıcıdaki yolun sıfırlandığını angular 2 yönlendirmesiyle çok tuhaf bir sorun yaşıyorum. orijinal rotaAngular2 yönlendirme sorunu ve ngOnInit iki kez çağrıldı

MaintenanceModule'da NotificationListComponent ve NotificationEditComponent var. Benim kökü AppModule yılında

, ben kurulum RouterModule/maintenance/list herhangi bağlanılmayan yolları yönlendirmek için.

@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 { } 

Ve benim NotificationListComponent işaret benim MaintenanceModule tanımlanan /maintenance/list güzergahı, hem de benim NotificationEditComponent de işaret eden /maintenance/edit/:id rota:

app.module.ts.

maintenance.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 {} 

başvurum yükler, doğru /maintenance/list güzergahını takip ve ben bir listede benim bildirimlerinin tümünü görebilirsiniz.

@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; 
    } 
} 

bildirim listesi: listedeki her bildirim için benim NotificationListComponent

bildirim list.component.ts içinde edit(id: number) yönteme bağlı olarak click olay olan bir düzenleme simgesi vardır .component.html: Gördüğünüz gibi

<div class="row"> 
    <h1>Notification Maintenance</h1> 

    <div *ngIf="errorMessage" class="alert-box alert"> 
    <span>{{errorMessage}}</span> 
    <a class="right" (click)="clearError()">&times;</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) yöntem gidin gerekir /maintenance/edit/:id rotası. Bu rotaya gitmek için simgeyi tıklattığımda, tarayıcı adres çubuğunda doğru yolu yanıp söner (ör. localhost:4200/#/maintenance/edit/2), ancak adres çubuğundaki rota hemen geri localhost:4200/#/maintenance/list olarak değişir. Rota, adres çubuğuna /maintenance/list döndü bile, benim gerçek uygulamada NotificationEditComponent hala görülebilir. Ancak, NotificationEditComponent benim iki kez çağrılırken görebildiğim, id konsol için iki kez oturum açtı ve ngOnInit işlevinde bir kesme noktası koyarsanız, bu kesme noktasına iki kez vurur.

bildirim 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 
    ); 
    } 
} 

Bu aynı zamanda örneğin [(ngModel)]="notification.notificationId", değer için, benim NotificationEditComponent kullanarak değerlere input değerlerini bağlamak için çalışırken, çünkü diğer konular neden oluyor gibi görünüyor Augury krom uzantısı ile görebiliyor olmama rağmen nesnenin konsola giriş yapmasına rağmen, ekranda bileşenin içinde yer almıyor olmasına rağmen ekranda görüntülenmiyor.

notification-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()">&times;</a> 
    </div> 

    <p-fieldset [legend]="'Edit Notification'"> 
    <label for="notificationId">ID: 
     <input id="notificationId" type="number" disabled [(ngModel)]="notification.notificationId"/> 
    </label> 
    </p-fieldset> 

</div> 

kimse bu oluyor neden bir fikri var mı?

Güncelleme:

Ben NotificationService benim aramaları kaldırıldı ve sadece bazı sahte verilerle bunları yerini ve sonra yönlendirme çalışmaya başladı! Ancak, servisime çağrı eklediğimde, yukarıda anlattığım aynı sorunu ele alıyorum. Hatta CoreModule'u kaldırdım ve servisi doğrudan benim MaintenanceModule'a ekledim ve yalnızca sahte veri yerine gerçek hizmeti kullandığımda hala aynı sorunu yaşıyorum.

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!'); 
    } 
} 

Ve hizmet iyi gidiyor - Ben son nokta başarıyla veri döndüren görebilir ve ben baktığınızda verilerin doğru bakar görebilirsiniz benim Augury krom uzantısı ile NotificationEditComponent. Ancak, veriler şablonda gösterilmiyor ve /maintenance/edit/:id rotası için şablon hala görüntüleniyor olsa bile URL'deki rota /maintenance/list'a dönüyor.

Güncelleme 2: Ben "düzenlemek birini tıkladığında o çıkışında İşte

constructor(private _router: Router) { 
    this._router.events.pairwise().subscribe((event) => { 
    console.log(event); 
    }); 
} 

edilir:

@ user3249448 önerdiği gibi, bazı hata ayıklama için benim AppComponent için aşağıdaki eklendi "bağlantıları:

Route logging

+0

En son Angular2 sürümünü kullanıyor musunuz? Bir süre önce bu davranışa neden olan ancak bir süre önce AFAIR'ın düzeltildiği bir sorun vardı. –

+0

Joker rotayı kaldırmayı ve sorunun giderilip giderilmediğini görün. Listede sonuncu olması gereken joker karakterlerle ilgili bir şeyler okumayı hatırlıyorum ve yapılandırmanızda bu kadar emin değilim. – wolfhoundjesse

+0

Kullanıyorum ** 2.4.8 ** ve '@ açısal/yönlendirici 'sürümü ** 3.4.8 **. Ve sorun hala, joker rotası olmadan bile gerçekleşir. –

cevap

5

Nihayet @ user3249448'den hata ayıklama yardımını aldıktan sonra sorunu çözebiliyordu. enter image description here

İşte

tam yığın izleme oldu:

Ben hiçbir hata konsoluna açmış ediliyordu rağmen bu NavigationError başlamıştı Meğerse Yani esasen

TypeError: Cannot read property 'notificationId' of undefined 
    at CompiledTemplate.proxyViewClass.View_NotificationEditComponent0.detectChangesInternal (/MaintenanceModule/NotificationEditComponent/component.ngfactory.js:487:49) 
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (http://localhost:4200/vendor.bundle.js:80125:14) 
    at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (http://localhost:4200/vendor.bundle.js:80320:44) 
    at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (http://localhost:4200/vendor.bundle.js:80110:18) 
    at CompiledTemplate.proxyViewClass.View_NotificationEditComponent_Host0.detectChangesInternal (/MaintenanceModule/NotificationEditComponent/host.ngfactory.js:29:19) 
    at CompiledTemplate.proxyViewClass.AppView.detectChanges (http://localhost:4200/vendor.bundle.js:80125:14) 
    at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (http://localhost:4200/vendor.bundle.js:80320:44) 
    at ViewRef_.detectChanges (http://localhost:4200/vendor.bundle.js:60319:20) 
    at RouterOutlet.activate (http://localhost:4200/vendor.bundle.js:65886:42) 
    at ActivateRoutes.placeComponentIntoOutlet (http://localhost:4200/vendor.bundle.js:24246:16) 
    at ActivateRoutes.activateRoutes (http://localhost:4200/vendor.bundle.js:24213:26) 
    at http://localhost:4200/vendor.bundle.js:24149:58 
    at Array.forEach (native) 
    at ActivateRoutes.activateChildRoutes (http://localhost:4200/vendor.bundle.js:24149:29) 
    at ActivateRoutes.activate (http://localhost:4200/vendor.bundle.js:24123:14) 

benim web servisime çağrı gönderilmeden önce şablon oluşturuldu ve şablonum düzgün işlenemedi çünkü notificationundefined idi, bu yüzden bu'u aldım Tanımlanan davranışa neden olan(bu hata, AppComponent ürününüzde ek hata ayıklama kodu eklemeniz gerekmeden konsolda oturum açmış gibi görünmüyor mu?).

Bunu düzeltmek için, tek yapmam gerekenbenim notification ile ilgili tüm bilgileri içeren eklemek oldu.

<p-fieldset [legend]="'Edit Notification'" *ngIf="notification"> 

Ve şimdi şablon yükler düzgün veri web hizmetinden döndürülen bir kez.

+0

Ücretsiz ipucu, elvis operatörünü de kullanabilirsiniz http://stackoverflow.com/questions/34833358/angular-2-typeerror-l-thing0-is-undefined-in-thing-title-in-appcomponent/34833436#34833436 –

+0

Resmi belgeler burada: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator –

0

Benim tahminim tarayıcı gerçek li olarak düzenle bağlantısını yorumluyor olurdu nk yerine yapmak istediğinizi yapmak. Bu, bir flaş gördüğünüz gerçeğine dayanır - tarayıcı, söz konusu bağlantıyı ziyaret etmeye çalışıyormuş gibi geliyor.

Bildirimi bir bağlantı etiketinden basit bir açıklığa veya div'e düzenlemek için, bildirim listenize tıklattığınız öğeyi değiştirmeyi deneyin. Flaşı almazsan, senin sorununun olduğunu biliyorsun.

+0

Hayır, bir işe yaramadı. Ve yanıp sönen asıl sayfa değil. Sayfa aslında düzenleme şablonunu doğru bir şekilde oluşturuyor (modele doğru bir şekilde giriş yapmıyorsa), yalnızca doğru düzenleme yoluna yanıp sönen adres çubuğu ve daha sonra liste yoluna geri dönülür, düzenleme şablonu ise asıl sayfada görüntülenir. . –