我在Angular有点新:

当我加载我的Angular应用程序(Angular 4)时,即使没有渲染,也会调用特定组件的ngOnInit()方法 . 在我将应用程序导航到呈现此组件的路径后,再次调用ngOnInit() . 这是为什么?这是某种错误,或者它是如何工作的?控制台中没有错误 .

(因此,在我的组件的ngOninit()中,一个订阅方法运行两次 . )

Update:

提供-info.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' },
...