Search code examples
angularjsangularjs-scopetypescripttypescript1.4typescript1.5

Angular+TypeScript: How to get method using HTTP Put


I am trying to fetch my all dropdown at page load using ANgularJs+TypeScript.I am done with implementing ng-options and ng-init method to load it but there might me some problem thats why i am not able to get my data from my API or to give call to my API.I have given my Code with this question.

Here is my typescript Controller:-

/// <reference path="../interface/interface.ts" />
/// <reference path="../../scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../../scripts/typings/angularjs/angular.d.ts" />

module CustomerNew.controllers {
    export class CreateCustomerCtrl {
        static $inject = ['$scope', '$http', '$templateCache'];
        debugger;
        constructor(protected $scope: ICustomerScope,
            protected $http: ng.IHttpService,
            protected $templateCache: ng.ITemplateCacheService) {
            $scope.create = this.create;
            $scope.getFormData = this.getformData;
        }
        public getformData: (getFormData: any) => {
            $http.get();
        }

Giving Error AS It's giving error of "Property or signature expected" & Unexpected token. "A constructor, method, accessor, or property was expected". Updated Error


Solution

  • We need this. and "=" to assign getformData

     constructor(protected $scope: ICustomerScope,
            protected $http: ng.IHttpService,
            protected $templateCache: ng.ITemplateCacheService) {
            $scope.create = this.create;
            $scope.getFormData = this.getformData;
     }
     //public getformData: (getFormData: any) => {
     public getformData = (getFormData: any) => {
        // instead of this notation
        // $http.get(...
        // we need to use this.
        this.$http.get(...
     }
    

    This could be some more complex example of the above TypeScript controller defintion:

    module CustomerNew.controllers
    {
        export interface ICustomerScope extends ng.IScope
        {
            create: Function;
            getFormData: Function;
        }
        export class CreateCustomerCtrl {
            static $inject = ['$scope', '$http', '$templateCache'];
            debugger;
            constructor(protected $scope: ICustomerScope,
                protected $http: ng.IHttpService,
                protected $templateCache: ng.ITemplateCacheService) {
                $scope.create = this.create;
                $scope.getFormData = this.getformData;
            }
            public getformData = (getFormData: any) =>
            {
                this.$http.get("url"); // ...
            }
            public create = () => { }
        }
    }
    

    Check it in this typescript playground compiler/transpiler