darkxahtep / angular-progress-http Goto Github PK
View Code? Open in Web Editor NEW[DEPRECATED] Use @angular/common/http instead
License: MIT License
[DEPRECATED] Use @angular/common/http instead
License: MIT License
Use Istanbul and TypeScript source maps for code coverage and coveralls.io as the coverage reporting tool
Hi !
I try this lib but I don't have percentage on my download, it's always undefined.
here my simple code (download file works)
public getInstallerNew = (): Observable<Response> => { this.headers.set('Authorization', 'Basic ' + getToken(this._router)); return this._httpProgress.withDownloadProgressListener(progress => { console.log('Downloading ' + progress.percentage + '%'); }).get(this.url + "download/app", {responseType: ResponseContentType.Blob, headers: this.headers}); };
console write "Downloading undefined%" about 200 times
While running npm run build, getting below error,
Could you please help me to understand the issue?
[email protected] copy-ts C:\Siva\Devlopment\angular-progress-http
copyup 'src/**/*' build
[email protected] transform-package C:\Siva\Devlopment\angular-prog
ess-http
node scripts/transformPackageJson.js
fs.js:558
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open 'C:\Siva\Devlopment\angular-prog
ess-http\build\package.json'
at Object.fs.openSync (fs.js:558:18)
at Object.fs.writeFileSync (fs.js:1223:33)
at Object. (C:\Siva\Devlopment\angular-progress-http\scripts\tra
sformPackageJson.js:11:4)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
I cannot seems to use a custom Http implementation. Maybe I do something wrong or maybe this is because I use Angular 4.
I get this error :
TypeError: this.http.request is not a function
in the request()
method of ProgressHttp
.
Here is my Http factory (derived from angular2-adal). The console.log
do display a correct HttpAuth
object as expected :
import { Injectable } from '@angular/core';
import { ConnectionBackend, RequestOptions } from '@angular/http';
import { HttpFactory, AngularHttpFactory } from 'angular-progress-http';
import { AuthService } from './auth.service';
import { HttpAuth } from './http-auth.service';
@Injectable()
export class HttpAuthFactory implements HttpFactory {
constructor(
private authService: AuthService,
private angularHttpFactory: AngularHttpFactory
) {}
public create(backend: ConnectionBackend, requestOptions: RequestOptions) {
const http = this.angularHttpFactory.create(backend, requestOptions);
let httpAuth = new HttpAuth(http, this.authService);
console.log(httpAuth);
return httpAuth ;
}
}
My Http implementation (derived from angular2-adal) :
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptionsArgs, RequestOptions, RequestMethod, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpAuth {
constructor (private http: Http, private authService: AuthService) {}
get(url: string, options?: RequestOptionsArgs): Observable<any> {
let options1 = new RequestOptions({ method: RequestMethod.Get });
options1 = options1.merge(options);
return this.sendRequest(url, options1);
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
let options1 = new RequestOptions({ method: RequestMethod.Post, body: body });
options1 = options1.merge(options);
return this.sendRequest(url, options1);
}
delete(url: string, options?: RequestOptionsArgs): Observable<any> {
let options1 = new RequestOptions({ method: RequestMethod.Delete });
options1 = options1.merge(options);
return this.sendRequest(url, options1);
}
patch(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
let options1 = new RequestOptions({ method: RequestMethod.Patch, body: body });
options1 = options1.merge(options);
return this.sendRequest(url, options1);
}
put(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
let options1 = new RequestOptions({ method: RequestMethod.Put, body: body });
options1 = options1.merge(options);
return this.sendRequest(url, options1);
}
head(url: string, options?: RequestOptionsArgs): Observable<any> {
let options1 = new RequestOptions({ method: RequestMethod.Put });
options1 = options1.merge(options);
return this.sendRequest(url, options1);
}
private sendRequest(url: string, options: RequestOptionsArgs): Observable<string> {
//make a copy
let options1 = new RequestOptions();
options1.method = options.method;
options1 = options1.merge(options);
if (!options1.headers) {
options1.headers = new Headers();
}
options1.headers.set('Authorization', 'Bearer ' + this.authService.token);
return this.http.request(url, options).map(this.extractData).catch(this.handleError);
}
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
var body = {};
//if there is some content, parse it
if (res.status != 204) {
body = res.json();
}
return body || {};
}
private handleError(error: any) {
// In a real world app, we might send the error to remote logging infrastructure
let errMsg = error.message || 'Server error';
console.error(JSON.stringify(error)); // log to console instead
return Observable.throw(error);
}
}
In my module:
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
VersionFormComponent,
LoginComponent
],
imports: [ // import Angular's modules
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(ROUTES, { useHash: true, preloadingStrategy: PreloadAllModules }),
Select2Module,
NgbModule.forRoot(),
ProgressHttpModule
],
providers: [ // expose our Services and Providers into Angular's dependency injection
ENV_PROVIDERS,
APP_PROVIDERS,
DataService,
AuthService,
{ provide: HTTP_FACTORY, useClass: HttpAuthFactory }
]
})
If I remove the last provider entry (HTTP_FACTORY), it works again but of I course it doesn't use my custom implementation
Hello,
I checked the data received in the progress listener but the path is not populated
thanks
Hi,
I am getting this error after ProgressHTTP to my project:
ERROR Error: Uncaught (in promise): Error: No provider for ProgressHttp!
Error: No provider for ProgressHttp!
at injectionError (reflective_errors.ts:71)
at noProviderError (reflective_errors.ts:105)
at ReflectiveInjector_.throwOrNull (reflective_injector.ts:500)
at ReflectiveInjector.getByKeyDefault (reflective_injector.ts:543)
at ReflectiveInjector.getByKey (reflective_injector.ts:404)
at ReflectiveInjector.get (reflective_injector.ts:349)
at CaPPModuleInjector.get (module.ngfactory.js:320)
at CaPPModuleInjector.get (module.ngfactory.js:325)
at CaPPModuleInjector.getInternal (module.ngfactory.js:1113)
at CaPPModuleInjector.NgModuleInjector.get (ng_module_factory.ts:141)
at injectionError (reflective_errors.ts:71)
at noProviderError (reflective_errors.ts:105)
at ReflectiveInjector_.throwOrNull (reflective_injector.ts:500)
at ReflectiveInjector.getByKeyDefault (reflective_injector.ts:543)
at ReflectiveInjector.getByKey (reflective_injector.ts:404)
at ReflectiveInjector.get (reflective_injector.ts:349)
at CaPPModuleInjector.get (module.ngfactory.js:320)
at CaPPModuleInjector.get (module.ngfactory.js:325)
at CaPPModuleInjector.getInternal (module.ngfactory.js:1113)
at CaPPModuleInjector.NgModuleInjector.get (ng_module_factory.ts:141)
at resolvePromise (zone.js:468)
at resolvePromise (zone.js:453)
at zone.js:502
at ZoneDelegate.invokeTask (zone.js:265)
at Object.onInvokeTask (ng_zone.ts:254)
at ZoneDelegate.invokeTask (zone.js:264)
at Zone.runTask (zone.js:154)
at drainMicroTaskQueue (zone.js:401)
at XMLHttpRequest.ZoneTask.invoke (zone.js:339)
Currently there are 2 separate example projects: upload-download
and custom-http
. Make it a single project with multiple example pages
Any plans for Angular 5 compatibility? We'll be forking this locally in our project. Would be happy to contribute if needed.
Now the upload mode is asynchronous. I want to change it into synchronous mode and upload one by one. Is that ok?
Hi developer,
I have seen that Progressive extends Http which is deprecated in angular 5.
Have you planned to migrate ad HttpClient?
Thanks
Best Regards
Create 1 or 2 tests (upload or upload & download) that will cover whole request flow from Angular component to server. Use xhr-mock if there will be no ability to use server in tests
OpaqueToken
is deprecated as of angular/core 4.0.0:
/*
* @deprecated since v4.0.0 because it does not support type information, use `InjectionToken<?>`
* instead.
*/
export declare class OpaqueToken {
protected _desc: string;
constructor(_desc: string);
toString(): string;
}
It should be replaced by typed InjectionToken<?>
:
/**
* Creates a token that can be used in a DI Provider.
*
* Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
* runtime representation) such as when injecting an interface, callable type, array or
* parametrized type.
*
* `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
* the `Injector`. This provides additional level of type safety.
*
* ```
* interface MyInterface {...}
* var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
* // myInterface is inferred to be MyInterface.
* ```
*
* ### Example
*
* {@example core/di/ts/injector_spec.ts region='InjectionToken'}
*
* @stable
*/
export declare class InjectionToken<T> extends OpaqueToken {
private _differentiate_from_OpaqueToken_structurally;
constructor(desc: string);
toString(): string;
}
Doc: https://angular.io/api/core/InjectionToken
Discussion: https://stackoverflow.com/questions/43419050/angular-2-opaquetoken-vs-angular-4-injectiontoken
I am not sure yet, since I've modified some code on my side.
It seems that after I upgraded to "@angular/http": "4.1.2"
it stopped working.
I'll check better, in the meanwhile does someone have the same issue?
Hi thanks for awesome work,
The download works as sweet
But for the upload, it shows the progress of upload but only after showing 100% percentage uploaded, it is hitting API and then API takes more time to send response back to client which makes as non-realistic progress
I am using Angular 5, .Net core API
Can you throw some light?
Hi,
I have a problem width the response on request.
I receive lengthComputable = false in response but in my php file i set a content length :
header("Content-Length: ".$size);
and when i look on postman the result of my request i see :
Content-Length →16102153
Can you help me ?
I'm getting the following error using the latest typescript - 2.4.1. Reverting to 2.3.2 fixed the issue
ERROR in C:/git/admin-veronica-ng/node_modules/angular-progress-http/lib/AngularHttpFactory.d.ts (3,22): Class 'AngularHttpFactory' incorrectly implements interface 'HttpFactory'.
Types of property 'create' are incompatible.
Type '(backend: ConnectionBackend, requestOptions: RequestOptions) => Http' is not assignable to type '<T extends Http>(backend: ConnectionBackend, requestOptions: RequestOptions)
=> T'.
Type 'Http' is not assignable to type 'T'.
Hi, I have issue trying to load it with SystemJs. Here is excerpt from my SystemJs config:
paths: {
'npm:': 'node_modules/'
},
map: {
'angular-progress-http': 'npm:angular-progress-http'
},
packages: {
'angular-progress-http': {
main: 'index.js',
defaultExtension: 'js'
}
}
I'm getting following error in browser:
Error: Unable to dynamically transpile ES module A loader plugin needs to be configured via SystemJS.config({ transpiler: 'transpiler-module' })
. Instantiating http://localhost:8090/node_modules/angular-progress-http/index.js
Do you have example working with SystemJs loader?
Add UMD bundle as a part of the library to be able to use it with SystemJS loader, issue described in #6
Use output throttling on node.js side if possible to make progress more illustrative and avoid using big files for it
This is a question rather than an issue,but i already have all my http requests in services, how can i migrate to angular-progress-http while keeping it in service ?
Thanks
I'm getting this error while trying to use ProgressHttpModule. Any ideas on why it happens?
It is common when developing with Typescript + NPM to ignore node_modules folder when compiling. By requiring your module to be compiled, we are forced to either enumerate all modules in the tsconfig that shouldn't be compiled or compile all of our node_modules, neither of which are particularly friendly. It would be preferable to include an index.js either instead of index.ts or additionally in a dist/ folder and refer to it from package.json.
I have an upload service which I access from a component. How can I send the upload progress from my service to my component?
From all the examples it looks like I cannot do this but have to have my service in my component which defeats the purpose of having a service.
upload.service.ts:
uploadSingleFileToServer(userFile) {
return this.http
.withUploadProgressListener(progress => { console.log(`Uploading ${progress.percentage}%`); }) // Inserted for testing
.post(this.url + '/upload', userFile)
.map(res => res.json());
}
app.component.ts:
onFileUploadSubmit(form: NgForm) {
const formData = new FormData();
formData.append('userFile', this.userFile);
formData.append('UserID', this.currentUID);
this.fileUploadSubscription = this.uploadService
.uploadSingleFileToServer(formData)
.subscribe(data => {
if (data.success) {
this._notificationService.success('File Upload', data.msg);
this.modalRef.hide();
this.mongoImages = [];
this.getFiles();
} else {
this._notificationService.error('File Upload', data.msg);
this.modalRef.hide();
}
});
}
As you can imagine, I want the progress in my component so that I can make use of it in the UI for the user.
Everything works when using ng serve, but when I use ng serve --prod there is inconsistent behaviour among different browsers. I do not get any errors or warning in the compiler or console.
Also I could not get the example project working out of the box because I got the following error:
ERROR in Error encountered resolving symbol values statically. Could not resolve angular-progress-http relative to C:/Users/chris/OneDrive/DEVtalk/Projects/Angular/angular-progress/examples/upload-download/src/app/app.module.ts., resolving symbol AppModule in C:/Users/chris/OneDrive/DEVtalk/Projects/Angular/angular-progress/examples/upload-download/src/app/app.module.ts, resolving symbol AppModule in C:/Users/chris/OneDrive/DEVtalk/Projects/Angular/angular-progress/examples/upload-download/src/app/app.module.ts
ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'C:\Users\chris\OneDrive\DEVtalk\Projects\Angular\angular-progress\examples\upload-download\src'
@ ./src/main.ts 4:0-74
@ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
My angular versions:
@angular/cli: 1.0.0
node: 6.9.5
os: win32 x64
@angular/animations: 4.2.5
@angular/common: 4.2.5
@angular/compiler: 4.2.5
@angular/core: 4.2.5
@angular/forms: 4.2.5
@angular/http: 4.2.5
@angular/material: 2.0.0-beta.7
@angular/platform-browser: 4.2.5
@angular/platform-browser-dynamic: 4.2.5
@angular/router: 4.2.5
@angular/service-worker: 1.0.0-beta.16
@angular/cli: 1.0.0
@angular/compiler-cli: 4.2.5
My code:
return this.http
.withUploadProgressListener(progress => {
console.log(progress.percentage);
this.requestProgress.emit(progress)
})
.post(url, body)
.map(response => response.json());
Browser behaviour:
IE => OK, in console I get an incremental percentage
Edge => NOK, in console I don't get an incremental percentage, only 100 at the end of the upload.
Chrome => NOK, I don't get anything in console
Firefox => NOK, I don't get anything in console
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.