Angular 4 ngOninit叫了两次

时间:2017-08-01 21:36:14

标签: html angular typescript angular2-template angular2-services

我已经查找了在其他问题和解答中给出的解决方案,但我仍然无法解决。问题是ngOnInit第一次在组件初始化时调用了两次。我将在下面分享代码以获取更多信息。

角度版

@ angular / cli:1.2.6 节点:6.10.3 os:darwin x64

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

1 个答案:

答案 0 :(得分:0)

我以某种方式创建了2个实例,谢谢!