gpt4 book ai didi

javascript - 如何在不影响模板的情况下用 Angular 模拟 REST

转载 作者:行者123 更新时间:2023-11-30 08:43:27 27 4
gpt4 key购买 nike

我只是在尝试 Angular 。

我想获取项目列表并在模板中显示它,现在只是对其进行硬编码,并想看看它如何与 ajax 一起工作。我没有休息服务器工作,正在尝试模拟 ajax 调用。

我刚刚尝试包括 Angular 模拟 e2e,但看起来它也覆盖了模板的 get 并抛出错误 Error: Unexpected request: GET views/main.html

有没有一种简单的方法我可以模拟 REST 请求并让模板与通常的 ajax 一起工作?

这不是单元测试或 e2e 测试场景,更多的是后端开发。我在主应用程序上而不是在测试中这样做。

我的 app.js 看起来像这样

'use strict';

var app = angular
.module('sabithangularApp', [
'ngResource', 'ngMockE2E'
]);
app.run(function ($httpBackend) {
var tasks = [{...},{....},{...}
];

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

$httpBackend.whenGET(/^\/templates\//).passThrough();
//...
});

控制台中的错误看起来像

Error: Unexpected request: GET views/main.html
No more request expected
at $httpBackend (http://127.0.0.1:9000/bower_components/angular-mocks/angular-mocks.js:1177:9)
at sendReq (http://127.0.0.1:9000/bower_components/angular/angular.js:7967:9)
at $http.serverRequest (http://127.0.0.1:9000/bower_components/angular/angular.js:7708:16)
at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11100:81)
at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11100:81)
at http://127.0.0.1:9000/bower_components/angular/angular.js:11186:26
at Scope.$eval (http://127.0.0.1:9000/bower_components/angular/angular.js:12175:28)
at Scope.$digest (http://127.0.0.1:9000/bower_components/angular/angular.js:12004:31)
at Scope.$apply (http://127.0.0.1:9000/bower_components/angular/angular.js:12279:24)
at http://127.0.0.1:9000/bower_components/angular/angular.js:1382:15

最佳答案

您需要为此添加一行额外的代码(在所有其他 .whenGET() 的下方)以忽略模拟 e2e,如下所示:

$httpBackend.whenGET(/.*/).passThrough();

这是一个包罗万象的所有(get)请求,没有任何其他行匹配。

编辑:

下面的行捕获所有以“view/”开头的请求:

$httpBackend.whenGET(/^views\/.*/).passThrough();

关于javascript - 如何在不影响模板的情况下用 Angular 模拟 REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com