如何在角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%');
}
}发布于 2017-05-27 15:25:10
您需要在可注入的服务中使用该变量,并使该服务共享。
服务
@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;
}
}希望能帮上忙!
https://stackoverflow.com/questions/44218488
复制相似问题