0
我已經查找了在其他問題和問題中給出的解決方案,但我仍然無法解決它。問題是ngOnInit首次調用組件時會調用兩次。我共享下面的代碼以獲取更多信息。Angular 4 ngOninit被調用兩次
角版本
@角/ CLI:1.2.6 節點:6.10.3 OS:達爾文64
@angular/cli: 1.2.6
@angular/common: 4.3.2
@angular/compiler: 4.3.2
@angular/compiler-cli: 4.3.2
@angular/core: 4.3.2
@angular/forms: 4.3.2
@angular/http: 4.3.2
@angular/platform-browser: 4.3.2
@angular/platform-browser-dynamic: 4.3.2
@angular/router: 4.3.2
//
import { DashboardService } from './../dashboard.service';
import { Component, OnInit, Input, NgZone } from '@angular/core';
import { RouterModule, Router } from "@angular/router";
import { MenuService } from './menu.service';
import { AuthService } from '../../auth/auth.service';
@Component({
selector: 'ca-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css'],
providers: [MenuService, AuthService]
})
export class MenuComponent implements OnInit {
@Input() showLogo = true;
sections: {}[];
selectedSection: number = 0;
constructor(
private _menuService: MenuService,
private _dashboardService: DashboardService,
private _router: Router, private _authService: AuthService,
) { }
ngOnInit() {
// let user_id = this._authService.getUserId();
// this.sections = this._menuService.getSections();
// this.sections.map(section => {
// let ignored_ids = section['ignored_ids'] ? section['ignored_ids'] : [];
// section['blocked'] = ignored_ids.indexOf(Number(user_id)) == -1 ? false : true;
// });
console.log('test');
}
setSection(section_name: String) {
// this._dashboardService.current_section.next(section_name);
}
}
//模板邊
<div *ngIf='sections'>
<div class="container-fluid logo" *ngIf="showLogo">
<img src="assets/logo_main.png">
</div>
<div *ngFor="let section of sections; let i=index">
<div class="menu-component d-block" *ngIf='!section.blocked' (click)='setSection(section.section_name)' [routerLink]="[section.url]" routerLinkActive="selected">
<i [class]="section.icon" aria-hidden="true" style="margin: 0 10px"></i> {{section.name}}
</div>
</div>
</div>
你可以顯示你使用這個組件的地方嗎?你確定你沒有創建2個實例嗎? –
@Jamil Alisgenderov你可以發佈你的app.module.ts?另外,看看這個Github問題鏈接:[Github問題](https://github.com/angular/angular/issues/6782) – mrsan22