公共变量在typescript中的函数中变为未定义

时间:2017-07-10 10:28:46

标签: angularjs typescript

我的代码如下所示:

/// <reference path="../../../typings/app.d.ts" />
/// <reference path="../../../typings/tsd.d.ts" />

module App.Controller {
    import Services = Core.Services;
    import Shared = Core.Shared;

    export class RestaurentInfoController extends BaseController {

        public restaurentName: any = [];
        public checkBox: any;
        public restaurent: any;
        public foodTruckList: any = [];
        public foodCategories: any = [];
        public drinkCategories: any = [];
        public restaurentId : any;

        static $inject: Array<string> = ['baseAppService', 'userAuthorizationService', 'storageService', 'eventService',];

        constructor(
            appService: Services.BaseAppService
            , public userAuthorizationService: Services.UserAuthorizationService,
            public storageService: Services.StorageService,
            public eventService: Services.AppEventBusService) {
            super(appService);
            this.getRestaurentList();
        }
        routeTo(view) {
            this.appService.routerService.routeToPage(view);
        }

        getRestaurentList = (): void => {
            this.appService.networkService.get<any>(this.appService.appConstant.appUrls.getFoodTruckName).then((response) => {
                this.foodTruckList = response.data;
            },
                (error) => { });
        }

        changeStatus = (): void => {
            if (this.checkBox === '1') {
                this.getFoodCategories();
            }
            else if (this.checkBox === '2') {
                this.getDrinkCategories();
            }
        }

        getFoodCategories = (): void => {
            console.log("rest " + this.restaurent);

            angular.forEach(this.foodTruckList, function (item) {
                console.log("here" + item.foodtruck_name);
                if(item.foodtruck_name === 'world in a box') {
                    console.log("match res "+ this.restaurent + " " + item._id);
                    this.restaurentId = item._id;
                    console.log("ressss "+ this.restaurentId);
                }
            });

            console.log("restaurentId "+this.restaurentId);
            this.appService.networkService.get<any>(`${this.appService.appConstant.appUrls.getFoodCategories}/${this.restaurentId}`).then((response) => {
                this.foodCategories = response.data;
                console.log('popuar Items Loaded', this.foodCategories);
            },
                (error) => { });
        }

        getDrinkCategories = (): void => {
            var data = {
                _id: this.restaurent._id
            }
            this.appService.networkService.get<any>(this.appService.appConstant.appUrls.getFoodTruckName, data).then((response) => {
                this.foodTruckList = response.data;
                console.log('popuar Items Loaded', this.foodTruckList);
            },
                (error) => { });
        }
    }

}

这里发生的事情是this.restaurentId显示带有ressss的console.log的值。但不知何故,当打印带有restaurentId的console.log时,该值变为未定义。我该怎么做才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

当您使用function() {}进行回调时,其中的上下文(this)会根据其调用方式而更改。要在回调中保留正确的上下文(即RestaurentInfoController实例为this),请使用arrow functions

angular.forEach(this.foodTruckList, (item) => {
  // ...
  console.log(this.restaurentId); // `this` will point to current `RestaurentInfoController` instance here
});