ngMockE2E - $ http不断返回<undefined>

时间:2017-04-10 11:28:16

标签: javascript angularjs ecmascript-6 httpbackend ngmocke2e

我一直在尝试在ES6中的Angular 1.6中编写应用程序,我想使用来自ngMockE2E的假HTTP后端: https://docs.angularjs.org/api/ngMockE2E/service/ $ httpBackend

所以我在home.run.js中实现了这样的API调用:

mocks.$inject = ['$httpBackend'];

export default function mocks($httpBackend) {

  let users = [{'name': 'Eva'},{'name': 'David'}] 

  $httpBackend.whenGET('/users').respond(users);

  $httpBackend.whenPOST('/users').respond(function(method, url, data) {
    let user = angular.fromJson(data);
    users.push(user);
    return [200, user, {}];
  });

}

我也有index.js,如下所示:

import angular from 'angular';
import uirouter from 'angular-ui-router';
import mocke2e from 'angular-mocks/ngMockE2E';

import mocks from './home.run'
import routes from './home.config';
import HomeController from './home.controller';

export default angular.module('app.home', [uirouter, mocke2e])
  .config(routes)
  .controller('HomeController', HomeController)
  .run(mocks)
  .name;

和HomeController一起调用get方法:

export default class HomeController {

 constructor($http) {
    this.$http = $http;
    this.users = this.getUsers();
 }

 getUsers() {
   this.$http.get('/users').then(function(response) {
     return response.data;
   });
 }

}

HomeController.$inject = ['$http']

不幸的是,即使在尝试不同的方法之后,控制器中的getUsers()方法仍然会从response.data返回undefined而不是用户。

是否有人能够弄清楚我搞砸了哪里?

1 个答案:

答案 0 :(得分:0)

您在return

中错过了getUsers()
export default class HomeController {

 constructor($http) {
    this.$http = $http;
    this.users = this.getUsers();
 }

 getUsers() {
   return this.$http.get('/users').then(function(response) {
     return response.data;
   });
 }

}