GVKun编程网logo

从未调用过AngularJS $ http错误函数(调用了未经初始化的对象或者是不存在的对象)

20

在这里,我们将给大家分享关于从未调用过AngularJS$http错误函数的知识,让您更了解调用了未经初始化的对象或者是不存在的对象的本质,同时也会涉及到如何更有效地Angular4中HTTP错误的集

在这里,我们将给大家分享关于从未调用过AngularJS $ http错误函数的知识,让您更了解调用了未经初始化的对象或者是不存在的对象的本质,同时也会涉及到如何更有效地Angular 4中HTTP错误的集中处理、Angular2 Http错误、AngularJS $http.post(..) – 错误:$http未定义、angularjs $http调用接口的方式详解的内容。

本文目录一览:

从未调用过AngularJS $ http错误函数(调用了未经初始化的对象或者是不存在的对象)

从未调用过AngularJS $ http错误函数(调用了未经初始化的对象或者是不存在的对象)

我有简单的代码:

$http.get("/api/test")    .success(function (data, status, headers, config) {        console.log(data);        return data;    }).error(function (data, status, headers, config) {        alert("error");        return status;});

它工作正常,但即使我从服务器返回404(未找到),也永远不会调用错误函数…在这种情况下,它会调用状态为404的“成功”函数…

那是对的吗?

谢谢

提琴手:

RequestGET http://localhost:41234/api/test HTTP/1.1Host: localhost:41234Connection: keep-aliveAccept: application/json, text/plain, */*X-Requested-With: XMLHttpRequestUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko)    Chrome/25.0.1364.172 Safari/537.22Referer: http://localhost:41234/Accept-Encoding: gzip,deflate,sdchAccept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3Cookie: ASP.NET_SessionId=bd1b3rib5j4beub0xbuhb1hm; FormsAuthentication=xxxxxResponseHTTP/1.1 404 Not FoundCache-Control: no-cachePragma: no-cacheExpires: -1Server: Microsoft-IIS/8.0X-AspNet-Version: 4.0.30319X-SourceFiles: =?UTF-8?B?RDpcUGVzc29hxvY2FyLkFwaVxhcGcg==?=X-Powered-By: ASP.NETContent-Length: 0

答案1

小编典典

问题出在您的Web服务器上,它将content-length设置为0,这意味着这是一个有效值,如您在HTTP /
1.1规范中所见。

我还在JSFiddle上举了一个例子,展示了错误和成功的例子。看这里。

错误示例的标头:

请求:

GET /error/ HTTP/1.1Host: fiddle.jshell.netConnection: keep-aliveAccept: application/json, text/plain, */*User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like  Gecko) Chrome/26.0.1410.65 Safari/537.31DNT: 1Referer: http://fiddle.jshell.net/danielcsgomes/cAMc6/1/show/Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Accept-Charset: UTF-8,*;q=0.5Cookie: csrftoken=4tNVNxC5v6BSq9yJCKkHlGFJBz3cClqd`

响应:

HTTP/1.1 404 NOT FOUNDServer: nginx/0.8.54Date: Fri, 12 Apr 2013 00:38:07 GMTContent-Type: text/html; charset=utf-8Transfer-Encoding: chunkedConnection: keep-aliveVary: CookieContent-Encoding: gzip

Angular 4中HTTP错误的集中处理

Angular 4中HTTP错误的集中处理

我想告知用户HTTP请求是否失败,而不必为每个HTTP请求编写额外的代码.

我有角度2的工作原型:

@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor() {
    super(false);
  }

  handleError(error: any) {
    this.tellUser(error);
    super.handleError(error);
  }

  tellUser(error: any) {
    // dig for the root cause
    if (error.rejection) {
      error = error.rejection;
    }
    if (error instanceof ViewWrappedError) {
       error = error.originalError;
    }

    let message;
    if (error instanceof Response) {
      // Todo: localize and display nicely
      const messages = {
        0: "Could not connect to server",}
      message = messages[error.status] || ("The server reported a system error (HTTP " + error.status + ")");
    } else {
      message = "A system error occurred.";
    }
    console.warn(message);
  }
}

但ViewWrappedError已被Angular 4替换为

export function viewWrappedDebugError(err: any,context: DebugContext): Error {
  if (!(err instanceof Error)) {
    // errors that are not Error instances don't have a stack,// so it is ok to wrap them into a new Error object...
    err = new Error(err.toString());
  }
  _addDebugContext(err,context);
  return err;
}

其中,由于在HttpResponse上调用toString,因此很难查询状态代码……

我希望angular能够为集中式错误处理提供一个公共的,支持良好的API.除了解析错误消息之外,真的没有办法集中处理HTTP错误吗?

更新:我更喜欢组件可以轻松覆盖集中式错误处理.

解决方法

另一种选择是简单地拥有一个委托给Http服务的服务,同时添加与API交互所需的任何自定义错误处理,调试逻辑,额外标题等.

然后,此服务成为您与Http相关的任何内容进行交互的集中点,因此您可以将错误处理集中在那里.在我开发的任何项目中,我总是创建这样一个类,因为几乎每个与之交互的API都有一些必须在每个请求中发生的常见配置(即使该配置与指定要使用的基本URL一样少).

这样一个类的例子:

export class ApiGateway {

  baseURL = "https://myapi.com";  // or sometimes pulled from another file
  constructor(private http: Http) { }

  get(path,params) {
    showLoadingIndicator();

    let headers = this.createMySpecialHeaders();
    let options = { headers: headers } // and whatever else you need to generalize
    let fullUrl = this.baseUrl + path + '?' + this.urlEncode(params)`;
    return this.get(path,params,options)
               .do(() => hideLoadingIndicator())
               .map(res => res.json())
               .catch(err => {
                    hideLoadingIndicator();
                  // show error message or whatever the app does with API errors etc
                  // sometimes rethrow the error,depending on the use case
                })
  }
}

对我来说,这是基本的OOP原则 – 在适配器类中包含与控件之外的事物的交互,以允许您对外部更改进行一些保护,并在必要时将该外部事物的API更改为您喜欢的内容.

如果有这样的类,例如,如果您升级到Angular 4并且接收错误的方法发生了变化,那么您只需要更改一个地方来处理新的错误技术.

Angular2 Http错误

Angular2 Http错误

我正在开始学习Angular2,遵循他们在页面上提供的 quickstart,现在我试图做一些 Http requests.但每当我启动组件时,Chrome会不断给我这个错误:
Uncaught SyntaxError: Unexpected token <         http:1
Uncaught SyntaxError: Unexpected token <         angular2-polyfills.js:138
   Evaluating http://localhost:3000/angular2/http
   Error loading http://localhost:3000/app/boot.js

这是组件:

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS,Http} from 'angular2/http';

@Component({
  selector: 'users',providers: [HTTP_PROVIDERS],templateUrl: 'app/views/users.html'
})
export class UsersComponent {

  people: Object[];
  constructor(http: Http) {
    http.get('http://192.168.56.101/api/test').subscribe(res => {
      this.people = res.json();
      console.log(this.people);
    });
  }
}

和引导:

import {bootstrap}    from 'angular2/platform/browser'
import {UsersComponent} from './components/users'

bootstrap(UsersComponent,[HTTP_PROVIDERS]);

只有{{people}}的观点.

TypeScript正在编译OK.我甚至不知道是什么失败!

文件缺乏这方面.路由器和Http需要添加到index.html.容易犯错误

AngularJS $http.post(..) – 错误:$http未定义

AngularJS $http.post(..) – 错误:$http未定义

我第一次尝试AngularJS.当使用$http.post(“url”,数据)功能时,我得到一个错误:$http没有定义控制台消息.

在我的HTML页面的顶部,我包括所有其他JS导入后的AngularJS.

我还包括其他JavaScript库由于小部件依赖关系等.我的脚本导入部分如下所示:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqgrid.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>

我有一个控制器,我用来发送一些数据到服务器:

function FormCtrl($scope) {
  $scope.sendData = function(){
        var data = "firstName=" + $scope.firstName + "&" +
            "lastName=" + $scope.lastName + "&" +
            "address=" + $scope.address + "&" +
            "postcode=" + $scope.postcode;

        $http.post("/data/person/put",data);
     };
}

sendData函数附加到一个按钮.所有的工作正常,直到调用$http.post(…),此时控制台输出错误.

完整的错误列表是:

Error: $http is not defined
$scope.sendData@http://localhost:8080/angularjs/:96
Mc/x/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:71
ec[c]</</</<@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:142
e.prototype.$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:87
e.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:87
ec[c]</</<@https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js:142
c.event.handle@http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:63
c.event.add/o@http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:57

https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js
Line 61

我需要做别的事情来配置AngularJS才能使用$http.post函数吗?

我从文件的“AngularJS快捷方式”部分直接提取了这些用法:http://docs.angularjs.org/api/ng.$http

谁能帮忙?

谢谢
亚当

函数FormCtrl($scope){应该是函数FormCtrl($scope,$http){.

您需要注入控制器所需的所有服务,在这种情况下,您使用$scope和$http服务,但是您只注入了导致错误的$scope.

例如:

function FormCtrl($scope,$http) {
    ....
}
FormCtrl.$inject = ['$scope','$http'];

您可以阅读关于注射并发症的注意事项,细化here,请参阅“Minifying注意事项”

angularjs $http调用接口的方式详解

angularjs $http调用接口的方式详解

如下所示:

rush:js;"> $http.get("/merchantmall/merchant.json") .success(function(data,status,headers,config) { console.log(arguments); }) .error(function(data,config) { console.log(arguments); })
rush:js;"> $http({url: "/merchantmall/merchant.json",}) .success(function(data,config) { console.log(arguments); })
rush:js;"> var promise = $http({ method: 'GET',url: '/api/users.json' }); promise.then(function(resp) { // resp是一个响应对象 },function(resp) { // 带有错误信息的resp });
rush:js;"> var promise = $http({ method: 'GET',url: '/api/users.json' }); promise.success(function(data,config) { // 处理成功的响应 }); promise.error(function(data,config) { // 处理非成功的响应 });

以上这篇angularjs $http调用接口的方式详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小编。

今天关于从未调用过AngularJS $ http错误函数调用了未经初始化的对象或者是不存在的对象的讲解已经结束,谢谢您的阅读,如果想了解更多关于Angular 4中HTTP错误的集中处理、Angular2 Http错误、AngularJS $http.post(..) – 错误:$http未定义、angularjs $http调用接口的方式详解的相关知识,请在本站搜索。

本文标签:

上一篇如何使AngularJS输出转义HTML(angularjs input)

下一篇防止在浏览器控制台中记录HTTP错误(防止在浏览器控制台中记录http错误怎么办)