A thin wrapper around Angular 2+ Http service that adds ability to work with upload/download progress
Import HttpModule and ProgressHttpModule
import { NgModule } from "@angular/core";
import { HttpModule } from "@angular/http";
import { ProgressHttpModule } from "angular-progress-http";
@NgModule({
imports: [
HttpModule,
ProgressHttpModule
]
})
export class AppModule {}
Inject ProgressHttp into your component and you are ready to go.See API description below for available methods.
import {Component} from "@angular/core";
import { ProgressHttp } from "angular-progress-http";
@Component({})
export class AppComponent {
constructor(private http: ProgressHttp) {
const form = new FormData();
form.append("data", "someValue or file");
this.http
.withUploadProgressListener(progress => { console.log(`Uploading ${progress.percentage}%`); })
.withDownloadProgressListener(progress => { console.log(`Downloading ${progress.percentage}%`); })
.post("/fileUpload", form)
.subscribe((response) => {
console.log(response)
})
}
}
npm install angular-progress-http@0.5.1
to get itFor release notes please see CHANGELOG.md
ProgressHttp service extends Http service provided by Angular/Http which means that you get all of the Http methods including
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response>;
get(url: string, options?: RequestOptionsArgs): Observable<Response>;
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
and others.
In addition it provides two methods for handling progress:
withDownloadProgressListener(listener: (progress: Progress) => void): HttpWithDownloadProgressListener;
withUploadProgressListener(listener: (progress: Progress) => void): HttpWithUploadProgressListener;
They both take callback as argument and return new instances of the service.
The interfaces returned from methods are described below:
interface HttpWithDownloadProgressListener extends Http {
withUploadProgressListener(listener: (progress: Progress) => void): Http;
}
interface HttpWithUploadProgressListener extends Http {
withDownloadProgressListener(listener: (progress: Progress) => void): Http;
}
Their purpose is to make libary easier to use and add compile-time checks for method calls
progressHttp //can use http api or call withUploadProgressListener or withDownloadProgressListener
.withUploadProgressListener(progress => {}) //can use http api or call withDownloadProgressListener
.withDownloadProgressListener(progress => {}) //here and on lines below can only use http api
.post("/fileUpload", form)
.subscribe((response) => {})
This restriction is used to make sure that there are now repeating calls to add progress listeners that will overwrite previously assigned handlers and may confuse developer
Calls to both methods are immutable (return new instances and do not change the internal state of the service), so you may do next things
let http1 = this.progressHttp.withUploadProgressListener(progress => { console.log("Uploading 1") });
let http2 = this.progressHttp.withUploadProgressListener(progress => { console.log("Uploading 2") });
let http3 = http1.withDownloadProgressListener(progress => { console.log("Downloading 1") });
In the code above http1 and http2 will have different upload listeners. http3 will have same upload listener as http1 and a download listener
This behavior may be useful when uploading multiple files simultaneously e.g.
this.files.forEach(f => {
const form = new FormData();
form.append("file", f.file);
this.progressHttp
.withUploadProgressListener(progress => { f.percentage = progress.percentage; })
.post("/fileUpload", form)
.subscribe((r) => {
f.uploaded = true;
})
});
Both upload and download progress listeners accept single argument that implements Progress interface
interface Progress {
event: ProgressEvent, //event emitted by XHR
lengthComputable: boolean, //if false percentage and total are undefined
percentage?: number, //percentage of work finished
loaded: number, //amount of data loaded in bytes
total?: number // amount of data total in bytes
}
The library tries to rely on Angular code as much as possible instead of reinventing the wheel.
It extends BrowserXhr class with logic that adds event listeners to XMLHttpRequest and executes progress listeners.Other parts that are responsible for http calls (Http, XhrConnection, XhrBackend) are used as is,which means that angular-progress-http will automatically receive fixes and new features from newer versions of angular/http
If you want to use custom Http service with progress you need to follow certain steps.Let's review them on example of ng2-adal library - a library for accessing APIs restricted by Azure AD.
interface HttpFactory {
create<T extends Http>(backend: ConnectionBackend, requestOptions: RequestOptions): T;
}
This interface contains single method to create instances of class derived from Http.The create method accepts ConnectionBackend and default RequestOptions which are always required for Http to make creation of factory easier.
Let's examine AuthHttp (Http implementation from ng2-adal) constructor to understand what dependencies it has:
constructor(http: Http, adalService: AdalService);
As you can see, it needs an instance of http service and adalService to work properly.With this knowledge we can now create the factory class.
The factory for ng2-adal is quite simple and will look next way:
import { Injectable } from "@angular/core";
import { ConnectionBackend, RequestOptions } from "@angular/http";
import { AuthHttp, AdalService } from "ng2-adal/core";
import { HttpFactory, AngularHttpFactory } from "angular-progress-http";
@Injectable()
export class AuthHttpFactory implements HttpFactory {
constructor(
private adalService: AdalService,
private angularHttpFactory: AngularHttpFactory
) {}
public create(backend: ConnectionBackend, requestOptions: RequestOptions) {
const http = this.angularHttpFactory.create(backend, requestOptions);
return new AuthHttp(http, this.adalService);
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { ProgressHttpModule, HTTP_FACTORY } from 'angular-progress-http';
import { AuthHttpModule } from "ng2-adal/core";
import { AuthHttpFactory } from "./ng2-adal.http.factory.service";
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule,
ProgressHttpModule,
AuthHttpModule
],
providers: [
{ provide: HTTP_FACTORY, useClass: AuthHttpFactory }
],
bootstrap: [AppComponent]
})
export class AppModule { }
That's it.Now each time when you will call methods of ProgressHttp it will use your custom http implementation internally and add progress listeners to it.
npm install
npm run build
npm install
npm test
There are two example projects at the moment
npm install
npm start
Feel free to ask questions and post bugs/ideas in the issues, as well as send pull requests.
New use case that is supported by the HTTP client is Progress events. To receive these events, we create our HTTP request manually in the following way: longRequest() { const request = new HttpRe
angular-file-upload 详细介绍 angular-file-upload 是一款轻量级的 AngularJS 文件上传工具,为不支持浏览器的 FileAPI polyfill 设计,使用 HTML5 直接进行文件上传。 在线演示 特性 支持上传进度,在上传的时候,可以取消或者中止,支持文件拖拽(HTML5),目录拖拽(weikit),CORS, PUT(html5)/POST 方法
我们写网站呢 上传功能几乎是一定会用到的,这是一个灰常使用的插件,而且操作简单,非常容易使用,老规矩还是放一下API,走运的是,这个插件的API并不需要翻墙也看得到哦~ https://github.com/nervgh/angular-file-upload 进入正题,我们如何安装,还是老样子安利波npm npm install angular-file-upload 我们如何在项目中使用它呢
最近有个项目需求是上传文件,一般是压缩包。上传到服务器进行进一步的操作。且需要支持单、多文件上传 由于项目一直使用的是angularjs写的前端,所有学习研究了下它自己的上传插件,写了个demo。简单记录一下,留作笔记 angular-file-upload 插件的GitHub地址:点击跳转 api地址:点击跳转 官方案例:点击跳转 大部分逻辑都在代码注解中体现出来,不在累赘。直接贴代码 代码 1
之前 激动人心的 Angular HttpClient 这篇文章已经介绍过 HttpClient ,今天看到 angular-university 博客中介绍 HttpClient 的文章,内容很详细,我就简单做了整理。有兴趣的话,建议直接阅读 原文。 HttpClientModule 应用 导入新的 HTTP Module import {HttpClientModule} from '@ang
//html 包裹一层 a 标签 不软效果回事和原声js一样的 <div class="uploading form-group"> <input class="form-control" ng-model="fileItem.name" readonly/> <a href="javascript:;" class="choose-book"> <input type="file" nam
环境同前篇随笔,lizi在这里po下js代码 演示地址 http://runjs.cn/detail/o4a55204 <script> 'use strict'; angular.module('app', ['angularFileUpload']) .factory("myService",function(){ var
给定下面的代码(测试代码),对请求的文件只进行一次调用的最佳方式是什么?目前,每次按下按钮,都会完成一个XHR请求。 这是json数据文件 这是组件文件。它使用一个简单的模型文件(它只是一个具有id和name属性的类) 我不会把所有的东西都放在这里来引导应用程序。但这表明了这个想法。 多谢
本文向大家介绍Angular 2 简单类扩展angular的Http类,包括了Angular 2 简单类扩展angular的Http类的使用技巧和注意事项,需要的朋友参考一下 示例
模板作为简单的函数,可以由任意的方式构成。下面是一些常见的使用情况。 页面布局(layout) 让我们来声明一个 views/main.scala.html 模板来作为主要的布局模板: @(title: String)(content: Html) <!DOCTYPE html> <html> <head> <title>@title</title> </head> <body
useFetch �� React hook for making isomorphic http requests Main Documentation npm i use-http Features SSR (server side rendering) support TypeScript support 2 dependencies (use-ssr, urs) GraphQL suppo
问题内容: 我有这段可以很好地跨源工作的jQuery代码: 现在,我试图将其转换为Angular.js代码,但没有成功: 任何帮助表示赞赏。 问题答案: AngularJS调用$ http的方式如下所示: 或者可以使用快捷方式将其编写得更加简单: 有很多事情要注意: AngularJS版本更简洁(尤其是使用.post()方法) AngularJS将负责将JS对象转换为JSON字符串并设置标头(可自
我有一段jQuery代码可以很好地跨原点工作: 现在我尝试将其转换为Angular.js代码,但没有成功: 感谢任何帮助。