标签: angular-http

如何使$ httpBackend对URL查询参数的顺序不敏感?

我使用Angular.js $httpBackend来测试一些包装$http调用的服务(这是在ngMock中,而不是 ngMockE2E).

看来,喜欢的东西expectwhen对的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

16
推荐指数
2
解决办法
5703
查看次数

将Access-Control-Allow-Origin设置为*的Angular 2 http请求

我正在使用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)

angular-http angular

16
推荐指数
1
解决办法
5万
查看次数

如何通过catchError()正确传播错误?

我写了一个可用的函数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() …

rxjs angular-http rxjs6

15
推荐指数
1
解决办法
2万
查看次数

如何捕获Observable.forkJoin(...)中的错误?

两个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)

promise rxjs angular-http angular angular-httpclient

15
推荐指数
2
解决办法
1万
查看次数

从'response'拒绝'responseError'

有时,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 angular-http angular-http-interceptors

14
推荐指数
1
解决办法
6334
查看次数

angularjs $ http.get让json无法在服务层工作

我正在开发一个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 angularjs-service angular-http

12
推荐指数
1
解决办法
2万
查看次数

Angular替代$ http

在AngularJS中发送请求我使用builtin $ http服务.

我将使用什么来向Angular中的服务器发送请求?我找不到任何涉及该主题的文档.

javascript ajax angular-http angular

12
推荐指数
1
解决办法
1万
查看次数

Angular 2 http post params and body

我正试图通过我的角度应用程序进行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哪些工作正常运行请求从任何地方,但我的角度应用程序.到目前为止我做了什么:

  1. 传递原始查询而不是URLSearchParams.
  2. 没有身体传递请求.
  3. 传递RequestOptions中的所有值.
  4. 将params作为字符串传递.
  5. 传递身体作为params.
  6. 传递身体为JSON.stringify({"用户名":"不,谢谢","密码":"唐诺"}

控制台输出 RequestOptions

选项:{"method":null,"headers":{"Content-Type":["application/json"],"Accept":["application/json"],"X-CLIENT-ID":[" 380954038 "]," X-CLIENT-SECRET ":[" 5BgqRO9BMZ4iocAXYjjnCjnO7fHGN59WP8BTRZ5f "]},"身体":"{}", …

angular-http angular

12
推荐指数
2
解决办法
8万
查看次数

如何使用角度为4.3的新httpClient处理未经授权的请求(状态为401或403)

我有一个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

12
推荐指数
2
解决办法
2万
查看次数

如何使用RXJS每2分钟拨打一次http电话?

我有一项服务,每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分钟打一次电话,最好的办法是什么?

rxjs angular-http angular

11
推荐指数
2
解决办法
1万
查看次数