我使用Angular.js $httpBackend来测试一些包装$http调用的服务(这是在ngMock中,而不是 ngMockE2E).
看来,喜欢的东西expect和when对的URL查询参数的顺序是敏感的.例如,如果我这样做,$httpBackend.when('POST','/apiCall?X=1&Y=2').respond(/* ... */)或者如果我在$httpBackend.expectPOST('/apiCall?X=1&Y=2')URL中有Y = 2和X = 1而不是X = 1和Y = 2,则会出现URL不匹配.
我想以这样一种方式编写我的测试,即被测试的服务可以自由地更改URL查询字符串参数的顺序而不会破坏测试.我在$ httpBackend文档中找不到任何解决方法.这样做的正确方法是什么?
angularjs angular-http httpbackend angularjs-http angular-mock
我正在使用angular2和打字稿.
我正试图发布到我的邮件黑猩猩订阅列表.
我的代码到目前为止:
constructor(router: Router, http: Http){
this.router = router;
this.http = http;
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Access-Control-Allow-Origin', '*');
}
subscribe = () => {
var url = "https://thepoolcover.us10.list-manage.com/subscribe/post?u=b0c935d6f51c1f7aaf1edd8ff&id=9d740459d3&subscribe=Subscribe&EMAIL=" + this.email;
this.isSuccess = false;
this.http.request(url, this.headers).subscribe(response => {
console.log(response);
this.isSuccess = true;
});
}
Run Code Online (Sandbox Code Playgroud)
这是我在控制台中遇到的错误:
我现在收到此错误:Uncaught SyntaxError:Unexpected token <
目前的代码如下:
export class Footer{
email: string = "";
router : Router;
http : Http;
jsonp: Jsonp;
isSuccess: boolean = false;
constructor(router: Router, jsonp: Jsonp, http: Http){
this.router = router; …Run Code Online (Sandbox Code Playgroud) 我写了一个可用的函数pipe:
HandleHttpBasicError<T>()
{
return ((source:Observable<T>) => {
return source.pipe(
catchError((err:any) => {
let msg = '';
if(err && err instanceof HttpErrorResponse)
{
if(err.status == 0)
msg += "The server didn't respond";
}
throw {
err,
msg
} as CustomError
})
)
})
}
Run Code Online (Sandbox Code Playgroud)
我可以在我的这个方式使用这个功能HttpService:
checkExist(id:string)
{
return this.http.head<void>(environment.apiUrl + 'some_url/' + id)
.pipe(
HandleHttpBasicError(),
catchError((err:CustomError) => {
if(err.msg)
throw err.msg;
if(err.err.status == HttpStatusCodes.NOT_FOUND)
throw("It doesn't exist.");
throw(err);
})
)
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好.当我订阅时checkExist(),我得到一个很好的错误消息,因为HandleHttpBasicError首先捕获一个错误并将catchError() …
两个http调用完成后,我使用Observable.forkJoin()来处理响应,但如果其中任何一个返回错误,我怎么能捕获该错误?
Observable.forkJoin(
this.http.post<any[]>(URL, jsonBody1, postJson) .map((res) => res),
this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)
)
.subscribe(res => this.handleResponse(res))
Run Code Online (Sandbox Code Playgroud) 有时,200 ok即使出现错误,我正在使用的API也会返回.响应JSON对象将类似于:
{
error: true
}
Run Code Online (Sandbox Code Playgroud)
我已经构建了一个$ http response拦截器,只是检查这个错误并拒绝它.我希望它然后跳进我的responseError功能:
$httpProvider.interceptors.push(function($q) {
return {
response: function (response) {
if (response.data.error) {
// There has been an error, reject this response
return $q.reject(response);
}
return response;
},
responseError: function(rejection) {
// Display an error message to the user
...
return $q.reject(rejection);
}
}
});
Run Code Online (Sandbox Code Playgroud)
问题是,即使在拒绝响应之后,我的responseError函数也没有被调用.它被调用500错误等,所以我知道它正在工作.我希望拒绝做同样的事情.
来自文档:
responseError: interceptor gets called when a previous interceptor threw an error or resolved with a …Run Code Online (Sandbox Code Playgroud) 我正在开发一个angularjs应用程序作为我的angularjs学习的一部分.我有控制器,从那里我打电话给服务层.
leagueManager.service("teamsService", function($http){
var teams = {};
$http.get('data/teams.json').then(function(data) {
teams = data;
});
this.getTeams = function(){
return teams;
};
Run Code Online (Sandbox Code Playgroud)
});
我注意到由于$ http.get.then的异步性质,数据不会立即被检索,因此当我从控制器(teamsController)调用getTeams()时,我不会得到"团队",我会得到没有.
不知道如何解决这个问题?
第二次尝试: 在阅读下面的帖子建议的关于延迟和角度承诺之后,我尝试了以下但它仍然没有效果.我的变量团队没有按照我想要的方式进行填充,之后填充它们并且在我的UI中没有帮助:
我的控制器 teamController.js
leagueManager.controller('teamsController', function($scope, $location, teamsService, $routeParams){
//init function to initialize data when controller is called everytime.
var init = function(){
$scope.teams = [];
var promise = teamsService.getTeams();
promise.then(
function(data){
console.log("teams after promise:="+data);
$scope.teams = data;
}
,function(reason)
{
alert('Failed: ' + reason);
}
);
console.log("teams in the scope:="+$scope.teams);
};
init();
});
Run Code Online (Sandbox Code Playgroud)
这是我的 …
在AngularJS中发送请求我使用builtin $ http服务.
我将使用什么来向Angular中的服务器发送请求?我找不到任何涉及该主题的文档.
我正试图通过我的角度应用程序进行api调用.我想要做的是使用命令参数向api发送一个post请求.我已经做了很多服务器端测试以及完成传出请求,$_POST而且body数据永远不存在.因此,我很确定这个问题存在于这段代码中.
public post(cmd: string, data: object): Observable<any> {
const params = new URLSearchParams();
params.set('cmd', cmd);
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
params: params,
body: data,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post('http://t2w.dev/index.php', data, options)
.map(this.handleData)
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
我尝试了许多不同的JSON结构,data但这是我尝试发送的核心:
{
"Username": "No thanks",
"Password": "Donno"
}
Run Code Online (Sandbox Code Playgroud)
this.handleData并且this.handleError是一种将数据和错误作为参数的方法,并返回我想要的内容.
api设置为记录任何通过$_POST哪些工作正常运行请求从任何地方,但我的角度应用程序.到目前为止我做了什么:
URLSearchParams.控制台输出
RequestOptions选项:{"method":null,"headers":{"Content-Type":["application/json"],"Accept":["application/json"],"X-CLIENT-ID":[" 380954038 "]," X-CLIENT-SECRET ":[" 5BgqRO9BMZ4iocAXYjjnCjnO7fHGN59WP8BTRZ5f "]},"身体":"{}", …
我有一个auth-interceptor.service.ts处理请求
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Cookie} from './cookie.service';
import {Router} from '@angular/router';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set(Cookie.tokenKey, Cookie.getToken())});
// Pass on the cloned request instead of the original request.
return next.handle(authReq).catch(this.handleError);
}
private handleError(err: HttpErrorResponse): Observable<any> {
console.log(err);
if …Run Code Online (Sandbox Code Playgroud) typescript angular-http angular-http-interceptors angular angular-httpclient
我有一项服务,每2分钟拨打一次我的休息服务.在我的服务上,我有以下功能
getNotifications(token: string) {
const body = 'xxxxxxxxx=' + token;
return this.http.post('/rest/ssss/ddddddd/notificationcount', body, this.options)
.map((res) => res.json());
}
Run Code Online (Sandbox Code Playgroud)
在我的组件上,我调用我的服务函数来调用API.
this.notificationService.getNotifications(this.token).subscribe((data) => {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
我想每2分钟打一次电话,最好的办法是什么?
angular-http ×10
angular ×6
angularjs ×3
rxjs ×3
ajax ×1
angular-mock ×1
httpbackend ×1
javascript ×1
promise ×1
rxjs6 ×1
typescript ×1