我想将Google Analytics用于我的所有请求。我使用$ http和$ resource并且我的应用程序太大了,所以我不想创建任何包装函数。在AngularJS 1.4.5中,我可以跟踪所有请求并应用一些Google Analytics吗?
答案 0 :(得分:1)
您可以使用interceptor。通过实现拦截器API并将其推入visible_instructors
拦截器阵列。如果实施得当,您可以集中处理每个请求/响应。
以下是使用TypeScript和类语法的示例:
$httpProvider
如上面链接的文档所示,您也可以使用匿名工厂执行此操作:
class ErrorInterceptor {
static $inject = ['$q'];
constructor(private $q: ng.IQService) {}
public request = (config) => {
// Do something on success
return config;
}
public requestError = (rejection) => {
// Do something on error
return this.$q.reject(rejection);
}
public response = (response) => {
// Do something on success
return response;
}
public responseError = (responseFailure) => {
// Do something on error
// Handle error codes separately if needed, e.g.:
if (responseFailure.status === -1) {
} else if (responseFailure.status === 401) {
} else if (responseFailure.status === 403) {
} else if (responseFailure.status === 404) {
} else if (responseFailure.status === 500) {
} else if (responseFailure.status === 503) {
} else {
}
return this.$q.reject(responseFailure);
}
}
const ErrorInterceptorConfig = ['$httpProvider', ($httpProvider) => {
$httpProvider.interceptors.push('ErrorInterceptor');
}];
// Register the service and configuration:
angular.module('yourModule')
.service('ErrorInterceptor', ErrorInterceptor)
.config(ErrorInterceptorConfig);