在angular2中,
update.service.ts
public _progress$: Observable<number>;
private _progress: number = 0;
private _progressObserver: Observer<number>;
constructor(private _http:Http, private _configurationService: ConfigurationService,private _authenservice:AuthenticationService) {
this._progress$ = new Observable(observer => {
this._progressObserver = observer
});
}
....
uploadVideo(file:File):Promise<Video> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
authenCode = this._authenservice.authenticate(),
xhr: XMLHttpRequest = new XMLHttpRequest();
console.log('getVideos:authenCode is' + authenCode);
let path = this._configurationService.getAPI('API_VIDEOMANAGEMENT_UPLOAD');
console.log('upload video to:' + path);
xhr.open('POST', path, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('xhr status 200');
resolve(<Video>JSON.parse(xhr.response));
} else {
console.log('xhr status rejected:'+xhr.status);
reject(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this._progress = Math.round(event.loaded / event.total * 100);
this._progressObserver.next(this._progress);
};
formData.append("file", file, file.name);
xhr.send(formData);
});
}
在另一个组件home.component.ts
中 private _uploadProgressStatus:Observable<number>;
constructor(private _uploadService:UploadService) {
this._uploadProgressStatus = this._uploadService._progress$;
this._uploadProgressStatus.subscribe(
data => {
console.log('progress = '+data/100);
}); //if subscribe to this._uploadProgressStatus, no values are received...
this._uploadService._progress$.subscribe(
data => {
console.log('progress = '+data/100);
});
} // if subscribe to this._uploadService._progress$ ,numbers are received.
任何想法是什么原因?
答案 0 :(得分:0)
制作可观察的.share()
this._progress$ = new Observable(observer => {
this._progressObserver = observer
}).share();
需要导入运营商;
import 'rxjs'
或
import 'rxjs/add/operator/share'