javascript - 如何以 Angular 2 - 4 递增变量

标签 javascript angular typescript

如何以 Angular 2 - 4 递增变量

当我由于某些原因从第 1 页转到第 2 页时,此变量 (n) 不会增加。

我希望每次页面加载时变量 n 都会增加 1, 在我路由到此页面 20 次后,我想记录 20,

export class DashboardComponent implements OnInit, AfterViewInit {

  public n: number = 0; // I want to increment this.


  constructor(private router: Router) { }

  ngOnInit() { }

  ngAfterViewInit() {

    // google.charts.setOnLoadCallback(() => this.chart_1('500', '100%'));

    console.log('-------- ngAfterViewInit -------');

    let chartwidth1 = $('#curve_chart1').width();
    let chartwidth2 = $('#curve_chart2').width();

    if ( this.n === 0) {
      chartwidth1 += 0;
      chartwidth2 += 0;
    } else {
      chartwidth1 -= 50;
      chartwidth2 -= 50;
    }

    console.log(chartwidth1);
    console.log(chartwidth2);

    console.log(this.n); // 0
    this.n += 1;
    console.log(this.n); // 1

    // google.charts.setOnLoadCallback(() => this.chart_1((chartwidth1 - 80), '100%'));

    this.chart_1((chartwidth1 - 80), '100%');
    this.chart_2((chartwidth2 - 80), '100%');

  }



}

最佳答案

您需要在可注入(inject)服务中包含该变量并共享该服务。

服务

@Injectable()
 export class SharedService {
   public n:number;
 }

应用模块

@NgModule({
 imports: [BrowserModule,
          HttpModule],
  declarations: [AppComponent],
  providers: [SharedService],
  bootstrap: [AppComponent]
 }) export class AppModule { }

您的组件

import {SharedService} from 'path of service folder';
export class DashboardComponent implements OnInit, AfterViewInit {

constructor(private router: Router,private sharedService:SharedService) {
 }

 ngAfterViewInit() {
   this.sharedService.n +=1;
  }
}

希望对你有帮助!!

关于javascript - 如何以 Angular 2 - 4 递增变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218488/

相关文章:

javascript - 加载一次 HTML 对象并多次使用

javascript - 如果选中复选框,则删除值为 MRW 的选项

javascript - 创建一个具有 RouterModule 作为依赖项的 Angular 包

javascript - 使用 Typescript 时,如何创建类装饰器以将新方法混合到 React 组件中?

JavaScript/jQuery 签名板

javascript - PhoneGap 中 iPhone 5 的相机功能,图像被压扁

angular - TS2339 : Property 'href' does not exist on type 'HTMLElement'

javascript - 如何正确处理 typescript 中的 promisifyAll?

angular - 如何在angular2中导航到新标签

javascript - Angular:在 AJAX 成功时设置变量