Angular6-在构造函数外部使用服务-错误未定义

时间:2018-12-12 21:29:17

标签: angular angular-services

如果从OnInit()之外的函数或构造函数中调用服务,则将错误定义为服务是未定义的

感谢您的帮助。

如果未注释代码,从scramble()函数对该函数的调用将给出错误。

无法读取未定义的属性'getTripsByCriteria'

代码如下

export class UpcomingTripsComponent implements OnInit{
    private gridApi;
    title = "Upcoming Trips";
    trip_list: {};
    trips: UpcomingTripList;
    rowData: any;
    private gridColumnApi: any;
    last_hours: number = 1;
    next_hours: number = 4;
    msg: string ='';
    gridOptions: any;
    private headerHeight;
    private rowClassRules;
    private smallscreen: boolean = true;
    private firsttime: boolean = true;

constructor(private upcomingTripsService: UpcomingTripsService, @Inject('BASE_URL') private baseUrl: string) {
    if (sessionStorage.getItem("last_hours")) {
        this.last_hours = Number(sessionStorage.getItem("last_hours"));
    }
    if (sessionStorage.getItem("next_hours")) {
        this.next_hours = Number(sessionStorage.getItem("next_hours"));
    }
    this.headerHeight = 70;

    this.rowClassRules = {
        "interleaved-rows": function (params) {
            return (params.node.rowIndex % 2 !== 0);
        }
    };
    this.upcomingTripsService.getTripsByCriteria(this.last_hours, this.next_hours).subscribe(result => { //works here
        this.trips = JSON.parse(result.toString());
        this.rowData = this.trips.UpcomingTrips;
    }, error => console.error(error));

}
ngOnInit() {
    alert('in ngOnInit' + this.upcomingTripsService); //works
}

changeAutorefresh(event) {
    alert('in checkbox change');
    this.scrambleAndRefreshAll();
}
scrambleAndRefreshAll() {
    setInterval(this.scramble, 10000);
}
scramble(params: any) {
    alert('in scramble' + this.upcomingTripsService); //error

    //this.upcomingTripsService.getTripsByCriteria(this.last_hours, this.next_hours).subscribe(result => {
    //    this.trips = JSON.parse(result.toString());
    //    this.rowData = this.trips.UpcomingTrips;
    //}, error => console.error(error));
    var params1 = { force: true };
    this.gridApi.refreshCells(params1);
}

1 个答案:

答案 0 :(得分:4)

必须将this而不是组件实例(重新)分配给window。传递方法时,请使用箭头函数捕获this

scrambleAndRefreshAll() {
    setInterval(() => this.scramble(), 10000);
}

或使用bind

scrambleAndRefreshAll() {
    setInterval(this.scramble.bind(this), 10000);
}