标签: angular-http

非阻塞对PHP的Ajax请求

我正在使用PHP从远程服务器下载(大)文件,并通过单击网页上的下载按钮触发此下载.

因此,当我单击download网页上的按钮时,会向PHP函数发出Ajax请求(带有角度$http).该功能触发下载使用cURL.

与此同时,我想用Ajax向我的PHP站点发出其他请求.但Pending只要下载正在进行,所有其他Ajax请求都会显示状态.

所以基本上下载阻止了对PHP的所有其他请求.有什么办法可以避免这种堵塞吗?

php ajax curl angularjs angular-http

4
推荐指数
1
解决办法
1129
查看次数

$state.go 不符合承诺

我正在尝试实施基本的安全检查,以根据用户的权限集阻止用户访问某些状态:

'use strict';

var autoExecApp = angular.module("myApp", ['ui.router']);

autoExecApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
    $stateProvider
        .state('index', {
            url: '/index',
            templateUrl: 'partials/index.html'
        })
        .state('permission', {
            url: '/permission',
            templateUrl: 'partials/permissions.html'
        });
}]);

autoExecApp.run(['$rootScope', '$state', '$userRoles', function($rootScope, $state, $userRoles) {

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {

        event.preventDefault(); // prevent page from being loaded anyway
        $userRoles.hasPermissions(toState.name).then(function(data) {
            var result = data === "true";
            if (!result) {
                $state.go('permission');
            }
            else {
                $state.go(toState.name, toParams ,{notify:false});
            }
        });
    });
}]);
Run Code Online (Sandbox Code Playgroud)

现在的问题是我的状态改变发生在一个 promise 内。我很乐意让它同步 - 在这种情况下确实应该如此,但我很困惑为什么它不能异步工作。

如果我移动event.preventDefault()承诺的内部,它会起作用。但是状态变化分 2 …

javascript promise angularjs angular-http angular-promise

4
推荐指数
1
解决办法
1548
查看次数

在本地处理Angular $ http错误,并回退到全局错误处理

我有一个基于组件的Angular应用程序,其中各个组件加载它们各自的数据.发生错误时,我通常希望组件显示错误消息.

但是,在某些情况下,我希望组件忽略错误,并将其留给一些全局错误处理机制来捕获它.

拦截器:

angular.module("...").factory("httpInterceptor", function($q) {
    return {
        responseError: function(response) {
            // (1)
            return $q.reject("I AM CALLED FIRST") 
        }
})
Run Code Online (Sandbox Code Playgroud)

Serivce:

angular.module("...").service("myService", function($http){
    return {
        fetchData: function(){
            return $http.get("...")    
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

控制器:

angular.module("...").controller("MyController", function(myService){
    myService.fetchData()
        .then(function(){ ... })
        .catch(function() { 
           // (2) 
           //I AM CALLED LAST
        })
})
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,我希望在控制器中处理错误(在第(2)点).如果控制器决定忽略错误(省略catch),则仍然可以在拦截器中捕获错误.

问题是拦截器不知道控制器是否打算捕获错误,因为它是在控制器之前调用的.因此拦截器不知道它是否应该显示错误(我不想要全局和本地错误消息).

如何捕获控制器忽略的http错误?

error-handling angularjs angular-http

4
推荐指数
1
解决办法
2573
查看次数

CORS 发出相同的控制器,一种方法可以,另一种方法不行

我遇到了非常奇怪的错误。

我在控制器中有两种方法,它们由 angular js http get 事件调用。

第一个工作正常,第二个是抛出 CORS 错误,不确定这怎么可能,因为它们都在同一个控制器中。

这是我得到的错误: 在此处输入图片说明

这些是我在 angularjs 中所做的调用:

 $http({
        url: 'http://localhost:52876/api/Admin/GetLoanInfo',
        method: "GET",
        params: { loanID: querystringParam }
    }).success(function (data, status) {
        console.log(data);
        $scope.LoanDetailsVM.LoanStatus = data.LoanStatus;
    }).error(function (data, status) {
        console.log(data);
    });

    $http({
        url: 'http://localhost:52876/api/Admin/GetLoanCovenants',
        method: "GET",
        params: { loanID: querystringParam }
    }).success(function (data, status) {
        console.log(data);
    }).error(function (data, status) {
        console.log(data);
    });
Run Code Online (Sandbox Code Playgroud)

和控制器方法:

[HttpGet]
[Route("api/Admin/GetLoanInfo")]
public async Task<IHttpActionResult> GetLoanInfo(int loanID)
{

        LoanApplication newApplication = null;
        newApplication = db.LoanApplications.FirstOrDefault(s => s.LoanId == loanID);
        return …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-web-api angularjs angular-http

4
推荐指数
1
解决办法
1878
查看次数

Angular 2 Http RetryWhen

我正在尝试retryWhen在HTTP调用中使用.

尝试使用时,它完美地工作:

return this.http.get(`${environment.apiUrl}/track/${this.user.instance._id}/${this.currentPlayer.playlist.id}/next?s=${this.playerCounter}`, options)
      .timeout(500, new TimeoutError(`Timeout trying to get next track. [instanceId=${this.user.instance._id}]`))
      .retryWhen(attempts => {
        return Observable.range(1, 3).zip(attempts, i => i).flatMap(i => 3 === i ? Observable.throw(attempts) : Observable.timer(i * 1000));
      })
Run Code Online (Sandbox Code Playgroud)

如果出现超时错误,最多会尝试3次.

但是,总是有一个buuut,我想让它更抽象地用于各种用例,为此,我必须检查错误的类型.

只会重试TechnicalErros.

所以我尝试了这个没有成功.

.retryWhen(attempts => {
    return attempts.flatMap(error => {
      if(error instanceof TechnicalError) {
        return Observable.range(1, 3).zip(attempts, i => i).flatMap(i => 3 === i ? Observable.throw(attempts) : Observable.timer(i * 1000));
      } else {
        Observable.throw(error);
      }
    });
  })
Run Code Online (Sandbox Code Playgroud)

它首先尝试停止,不执行Observable.timer(),也不执行Observable.throw().

我几乎可以肯定问题是关于第一个 …

observable rxjs angular-http rxjs5 angular

4
推荐指数
1
解决办法
5039
查看次数

Angular 2/4 &amp; RxJS - forEach 内的订阅 - 确保在所有 Observable 完成之前不会继续流控制

目标是遍历一组 ID,为每个 ID 进行一次 HTTP 调用。对于每个 ID,我使用了一个带有 get() 方法的服务,该方法返回一个 Observable。每次调用 get() 方法时,我都会订阅返回的 Observable 并尝试将结果推送到一个数组中,该数组最终将传递给新操作的不同方法。

相关服务方式:

public get(departmentId: number): Observable<IDepartmentModel> {
    return super.get<IDepartmentModel>(departmentId);
}
Run Code Online (Sandbox Code Playgroud)

注意:超类正在利用 Angular Http,它经过充分测试并确认可以正常工作。逻辑的问题不在这里......

相关组件方法: 注意在 forEach 中多次调用的 DepartmentService.get() 调用。

 setInitialDepartmentsAssignedGridData(): void {
    this.settingsForDropdownSelectedCompanyId = this.userForm.get('defaultCompany').get('defaultCompanyId').value;

    let departments: IDepartmentModel[] = [];

    this.userService.user.getValue() //confirmed: valid user is being pulled back from the userService (logic is fine here..)
        .userCompanies.find(comp => comp.companyId === this.settingsForDropdownSelectedCompanyId) // getting a valid match here (logic is fine here..)
        .departmentIds.forEach(deptId => this.departmentService.get(deptId).first().subscribe(dept => { // getting …
Run Code Online (Sandbox Code Playgroud)

ajax observable rxjs angular-http angular

4
推荐指数
1
解决办法
2198
查看次数

带有方法 GET 的 Angular HttpClient 参数不起作用

我想问你关于 get 方法的参数。我有这样的事情:

    path = 'https://example.com/api';
    const params = new HttpParams();
    params.append('http', 'angular');
    return this.http.get(path, {params: params});
Run Code Online (Sandbox Code Playgroud)

我以为我会有这样的网址:

www.example.com/api?http=angular

但实际上,当我在 chrome 的网络选项卡中检查时,请求 url 是

www.example.com/api

当我想要路径时应该怎么做: www.example.com/api?http=angular 是否可以在没有 chrome 的情况下检查使用方法的请求 url?我的意思是在使用该方法的服务中?

http typescript angular-http angular

4
推荐指数
1
解决办法
2983
查看次数

以角度 2 进行并行调用 http get 或 post 调用

如何在 angular 2 中进行并行调用 HTTP get 或 post 调用?

我对一个愈伤组织的响应有 2 个服务呼叫必须拨打另一个电话。
有人可以建议我如何使用错误处理方案调用 make 这些并行调用吗?

rxjs angular-http angular

4
推荐指数
1
解决办法
1700
查看次数

Angular5 响应头(Content-Disposition)读取

如何读取响应标头(内容处置)?请分享分辨率。

当我检查 Postman 或 Google Chrome Network 选项卡时,我可以在 HTTP 调用的响应标头部分看到“Content-Disposition”,但无法读取 Angular Code 中的标头参数。

// Node - Server JS
app.get('/download', function (req, res) {
  var file = __dirname + '/db.json';
  res.set({
    'Content-Type': 'text/plain',
    'Content-Disposition': 'attachment; filename=' + req.body.filename
  })
  res.download(file); // Set disposition and send it.
});


// Angular5 Code
 saveFile() {
    const headers = new Headers();
    headers.append('Accept', 'text/plain');
    this.http.get('http://localhost:8090/download', { headers: headers })
      .subscribe(
        (response => this.saveToFileSystem(response))
      );
  }

  private saveToFileSystem(response) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition'); // <== Getting …
Run Code Online (Sandbox Code Playgroud)

angular-http

4
推荐指数
1
解决办法
6894
查看次数

在 ionic 4 上使用 Angular 7 后出现 Cors 策略错误

我很沮丧地发布了类似的问题,但花了 3 天多的时间却无法解决问题。

\n\n

平台:Ionic 4 Angular 7

\n\n

当我尝试发布时,出现 cors 政策错误。

\n\n

从来源 \' http://localhost:8100 \' 访问 \' https://mersinders.com/api/service.php?run=giris \'处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应不会未通过访问控制检查:它没有 HTTP 正常状态。

\n\n

当我禁用 chrome 安全性时,一切正常。

\n\n
\n

“C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe”\n --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp

\n
\n\n

HttpErrorResponse\xc2\xa0{标头:HttpHeaders,状态:400,statusText:“错误请求”,url:“ https://mersinders.com/api/service.php?run=giris ”,好的:false,\xc2\ xa0\xe2\x80\xa6}

\n\n

在 Php api 端使用以下标头后,问题开始出现。

\n\n
\n

header(\'状态: 400\', TRUE, 400); header(\'状态: 404\', TRUE, 404);

\n
\n\n

我有 config.ini.php 其中包括数据库信息和连接,以及 service.php 切换大小写 "service.php?run=XXXXX" 。

\n\n

当我在 service.php 中设置标头时

\n\n
\n

header(\'Access-Control-Allow-Origin: *\');
\n header("Access-Control-Allow-Credentials: true");
\n …

php header cors angular-http ionic4

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