首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在角2-4中增加变量

如何在角2-4中增加变量
EN

Stack Overflow用户
提问于 2017-05-27 15:15:34
回答 1查看 4.2K关注 0票数 0

如何在角2-4中增加变量

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

我希望每次页面加载变量n的增量为1,当我将20次路由到此页面后,我希望记录20,

代码语言:javascript
复制
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%');

  }



}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-27 15:25:10

您需要在可注入的服务中使用该变量,并使该服务共享。

服务

代码语言:javascript
复制
@Injectable()
 export class SharedService {
   public n:number;
 }

应用程序模块

代码语言:javascript
复制
@NgModule({
 imports: [BrowserModule,
          HttpModule],
  declarations: [AppComponent],
  providers: [SharedService],
  bootstrap: [AppComponent]
 }) export class AppModule { }

您的组件

代码语言:javascript
复制
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;
  }
}

希望能帮上忙!

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44218488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档