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

Angular6 - Using service outside of constructor - error as undefined

如果从 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);
}

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

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

或使用bind

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