如何以 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/