Angularjs在服务中使用$ http和$ cookies

时间:2018-01-15 11:46:26

标签: angularjs http cookies

当我尝试使用angular-cookie和$ http时出现错误: TypeError:无法读取未定义

的属性'then'

我是以错误的方式注射的吗?没有ng-cookies一切正常!

THX

static $inject = ['$rootScope','$http', '$cookies', '$q','$cookieStore','$window'];

constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public $http: ng.IHttpService, private $q: ng.IQService, public $cookieStore: ng.cookies.ICookieStoreService, public $cookies: ng.cookies.ICookiesService) {
}

loginUserOnApi (userData: any) {

    let deferred = this.$q.defer();
    let parameters = {
        username: userData.title,
        password: userData.password
    };

    let config = {
      params: parameters,
      withCredentials: true,
      headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
    };
    let self  = this;

    this.$http.get(this.loginApiUrl , config).then(response => {
        self.status = response.data['ack'];
        self.$cookies.putObject('new-acc-var',response);
        deferred.resolve(response.data);

    }).catch( reason => {
        deferred.reject(reason);
    });

    return deferred.promise;

   }

错误:

index.js:67374 TypeError: Cannot read property 'then' of undefined
at LoginService.loginUserOnApi (index.js:9794)
at LoginUserController.loginUserOverService (index.js:8911)
at fn (eval at compile (index.js:68225), <anonymous>:4:202)
at callback (index.js:80046)
at Scope.$eval (index.js:71116)
at Scope.$apply (index.js:71215)
at HTMLFormElement.<anonymous> (index.js:80051)
at defaultHandlerWrapper (index.js:56368)
at HTMLFormElement.eventHandler (index.js:56356)

1 个答案:

答案 0 :(得分:0)

static $inject = ['$rootScope','$http', '$cookies', '$q','$cookieStore','$window'];

constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public $http: ng.IHttpService, private $q: ng.IQService, public $cookieStore: ng.cookies.ICookieStoreService, public $cookies: ng.cookies.ICookiesService) {
}

检查 - 订单不正确。在$ inject http中排名第2,在函数中 - 第3位。