【问题标题】:Cannot read property 'http' of undefined in test - Angular 2+无法读取测试中未定义的属性“http”-Angular 2+
【发布时间】:2019-01-08 19:05:33
【问题描述】:

试图为我的测试获取一个新的令牌,但努力寻找原因......

我不确定这是否是最好的方式,或者我是否应该嘲笑它,但这是我现在想做的方式......

我得到的错误是:

TypeError: Cannot read property 'http' of undefined
        at getValidToken src/app/services/auth/auth.service.spec.ts:15:17)
        at Suite.<anonymous> src/app/services/auth/auth.service.spec.ts:31:22)
        at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
        at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run node_modules/zone.js/dist/zone.js:138:1)
        at Suite.<anonymous> node_modules/zone.js/dist/zone-testing.js:491:1)
        at Env.jasmineEnv.(anonymous function) [as fdescribe] node_modules/zone.js/dist/zone-testing.js:424:1)
        at Object../src/app/services/auth/auth.service.spec.ts src/app/services/auth/auth.service.spec.ts:8:1)

【问题讨论】:

  • “this”的范围在函数内部发生了变化。

标签: javascript angular types


【解决方案1】:

this 引用父函数,所以如果你这样做

  function getValidToken() {
    return this.http.post(apiBaseUrl + '/auth', postTokenJson)
    .then(map(tok => {
      return tok;
    }));
  }

你会得到一个错误,因为getValidToken 内部没有http 函数

解决方案是在这样的变量中实例化父“this”:

  var pThis=this;
  function getValidToken() {
    return pThis.http.post(apiBaseUrl + '/auth', postTokenJson)
    .then(map(tok => {
      return tok;
    }));
  }

【讨论】:

  • 如果我这样做,我会收到错误 Cannot read property 'post' of undefined,因为 post 现在只需要 1 个参数,即 url...
  • 你是否正确导入了HTTPModule和HTTP?
  • @physicsboy 您可能需要添加第三个参数,即postoptions 检查this,正如@Vinayak 所说,您需要检查 http 模块是否正确导入,this 也可能帮助
  • 是的,我已经正确导入了,不,不需要后置选项,它只是想要一个不可取的 url
猜你喜欢
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
相关资源
最近更新 更多