如何从 angular 的 $httpBackend 返回文件内容? [英] How to return a file content from angular's $httpBackend?

查看:24
本文介绍了如何从 angular 的 $httpBackend 返回文件内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以 angular 设置 e2e 测试套件,并且需要使用 $httpBackend 返回预设响应.如果我可以只返回文件内容就好了,例如

I'm trying to setup an e2e test suite in angular, and need to return canned responses using $httpBackend. It would be nice if I could just return a file content, e.g.

  $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
    return getContentOf("/somefile");
  });

我尝试使用 $http,类似于

I tried to use $http, something along the lines of

  $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
    return $http.get("/responses/phones.js");
  });

但它没有用,猜猜 angular 不支持从 $httpBackend 返回承诺?

but it didn't work, guess angular doesn't support returning promises from $httpBackend ?

我可以做到的一种方法是在应用加载时引用带有响应的 js 文件,并将文件的内容分配给变量,但能够按需加载数据会更好.

One way I could do it is to reference js files with responses on app load, and assign file's content to variables, but it would be much nicer to be able to load data on demand.

推荐答案

由于 $httpBackend 不适用于返回的 promise,因此您可以这样做的一种方法是同步获取数据.$http 没有开箱即用的同步选项,因此您必须在没有它的情况下调用您的文件,如下所示:

Since $httpBackend doesn't work with returned promises, one way you can do this is to get your data synchronously. $http doesn't have a synchronous option out of the box, so you would have to make the call to your file without it, like so:

$httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  var request = new XMLHttpRequest();

  request.open('GET', '/responses/phones.js', false);
  request.send(null);

  return [request.status, request.response, {}];
});

这篇关于如何从 angular 的 $httpBackend 返回文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆