Angular 2和跟踪文件上传进度

时间:2017-02-18 23:24:09

标签: angular xmlhttprequest progress-bar angular-http

我需要在上传文件时显示进度条。经过多次剽窃网后,从以下开始:

TL; DR

ProgressService未在CustomBrowserXhr中注入。

长版:

扩展BrowserXhr

import { ProgressService } from "./progress-service";

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor(private service:ProgressService) {
    super();
  }

   build(): any {
     let xhr = super.build();

      xhr.onprogress = (event) => {            
        this.service.downloadProgress.next(event);
      };

      xhr.upload.onprogress = (event) => {      
        this.service.uploadProgress.next(event);
      };

      return <any>(xhr);
  }
}

进度服务

@Injectable()
export class ProgressService {

  downloadProgress: Subject<any> = new Subject();
  uploadProgress: Subject<any> = new Subject();

}

引导(为简洁起见)

import { BrowserXhr }               from "@angular/http";
import { CustomBrowserXhr }         from "./services/custom-browser-xhr";
import { ProgressService }          from "./services/progress-service";

@NgModule({
    imports: [ 
       BrowserModule, 
       HttpModule, 
       FormsModule,
       Ng2Bs3ModalModule
    ],
    declarations: [ ],
    providers: [
        ProgressService,
        { provide: BrowserXhr, useClass: CustomBrowserXhr }
    ],
    bootstrap: [ 
        ApplicationComponent        
    ]
})
export class AppModule { }

问题是,ProgressSerice未注入CustomBrowserXhr。得到以下错误:

Uncaught TypeError: Cannot read property 'downloadProgress' of undefined
    at XMLHttpRequest.xhr.onprogress (custom-browser-xhr.ts:16)
    at XMLHttpRequest.wrapFn [as _onprogress] (zone.js:1039)
    at ZoneDelegate.invokeTask (zone.js:275)
    at Object.onInvokeTask (core.umd.min.js:35)
    at ZoneDelegate.invokeTask (zone.js:274)
    at Zone.runTask (zone.js:151)
    at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
xhr.onprogress @ custom-browser-xhr.ts:16
wrapFn @ zone.js:1039
ZoneDelegate.invokeTask @ zone.js:275
onInvokeTask @ core.umd.min.js:35
ZoneDelegate.invokeTask @ zone.js:274
Zone.runTask @ zone.js:151
ZoneTask.invoke @ zone.js:345
resume-service.ts:21 s

在下一行放置一个断点,确实发现servicenull

this.service.downloadProgress.next(event);

0 个答案:

没有答案