我对 Angular 有点陌生:
当我加载我的 Angular 应用程序 (Angular 4) 时,即使没有渲染特定组件的 ngOnInit() 方法,它也会被调用。在我将应用导航到呈现此组件的路由后,再次调用了 ngOnInit()。这是为什么?这是某种错误,还是它是这样工作的?控制台中没有错误。
(因此,在我的组件的 ngOninit() 中,订阅方法运行了两次。)
更新:
报价信息.component.ts:
import { Component, Input, OnInit, NgZone } from '@angular/core';
import { OfferService } from './offer.service';
import { Offer } from '../models';
declare var $: any;
@Component({
moduleId: module.id,
selector: 's2a-offer-info',
templateUrl: './offer-info.component.html',
})
export class OfferInfoComponent implements OnInit {
private zone: NgZone;
offer: Offer = null;
constructor(
private offerService: OfferService,
) { }
ngOnInit() {
//This is where I get two 'test' output on the console:
console.log('test');
this.zone = new NgZone({enableLongStackTrace: true});
this.offerService.getOfferForOfferInfo().subscribe((offer: Offer) => {
if (offer !== null) {
this.zone.run(() => {
this.offer = offer;
$('#s2aOfferInfoModal').modal();
});
}
});
}
}
在 page-packages.component.html 中:
...
<!-- This tag appers only once in the whole application: -->
<s2a-offer-info></s2a-offer-info>
...
在 app-routing.module.ts 中:
...
{ path: 'packages', component: PagePackagesComponent, canActivate: [LoggedInGuard] },
{ path: 'search', component: PageSearchComponent, canActivate: [LoggedInGuard] },
{ path: '', redirectTo: '/search', pathMatch: 'full' },
...