Example #1
0
 .flatMap(i => {
     let j1 = Observable.create(s => {
         $.get("http://localhost:8080/double?number=" + (i), d => s.next(d));
     });
     let j2 = Observable.create(s => {
         $.get("http://localhost:8080/double?number=" + (i + 100), d => s.next(d));
     });
     let j3 = Observable.create(s => {
         $.get("http://localhost:8080/double?number=" + (i + 1000000), d => s.next(d));
     });
     return Observable.merge(j1, j2, j3);
 })
    /**
     * 
     */
    count(db:IDBDatabase, storeName:string){
        return Observable.create( (observer:Subscriber<any>) => {
            let tnx: IDBTransaction = this.getTransaction(db, storeName, "readonly")
            let store: IDBObjectStore = this.getObjectStore(tnx, storeName)

            let countRequest: IDBRequest = store.count()
            
            let onSuccess = (ev:Event) => {
                this.logEvent("count", ev)
                observer.next(ev.target.result);
                observer.complete()
            }
            
            let onError = (ev:Event) => {
                this.logEvent("count", ev)
                observer.error(ev.target.error)
            }
            
            countRequest.addEventListener(IDB_EVENT_SUCCESS, onSuccess)
            countRequest.addEventListener(IDB_EVENT_ERROR, onError)
            
            return () => {
                countRequest.removeEventListener(IDB_EVENT_SUCCESS, onSuccess)
                countRequest.removeEventListener(IDB_EVENT_ERROR, onError)
            }
                
        })
    }
Example #3
0
 export function fromEventSource(source: sse.IEventSourceStatic, event: string, openObserver:rx.Observer<Event> = undefined):rx.Observable<Event> {

    return rx.Observable.create(function (observer:rx.Observer<Event>) {
        function onOpen(e:Event) {
            openObserver.next(e);
            openObserver.complete();
            source.removeEventListener('open', onOpen, false);
        }

        function onError(e:any) {
            source.close();
            if (e.readyState === EventSource.CLOSED) {
                observer.complete();
            } else {
                observer.error(e);
            }
        }

        function onMessage(e:Event) {
            observer.next(e);
        }

        openObserver && source.addEventListener('open', onOpen, false);
        source.addEventListener('error', onError, false);
        source.addEventListener(event, onMessage, false);

        return function () {
            source.removeEventListener('error', onError, false);
            source.removeEventListener(event, onMessage, false);
        };
    });
}
    public getPhoto(): Observable<string> {
        return Observable.create((observer: Observer<string>) => {
            let removeDomListener = () => {
                document.removeEventListener('deviceready', onCordovaDeviceReady);
            };

            let onCordovaDeviceReady = () => {
                const camera = window.navigator.camera;

                let options = {
                    quality: 50,
                    destinationType: camera.DestinationType.DATA_URL,
                    sourceType: camera.PictureSourceType.CAMERA,
                    encodingType: camera.EncodingType.PNG,
                    saveToPhotoAlbum: false,
                    correctOrientation: true
                };

                camera.getPicture(imageData => {
                    observer.next('data:image/png;base64,' + imageData);
                    removeDomListener();
                    observer.complete();
                }, error => {
                    observer.error(error);
                    removeDomListener();
                    observer.complete();
                }, options);
            };

            document.addEventListener('deviceready', onCordovaDeviceReady);
        });
    }
    public runWorker(): Observable<string> {
        var self = this;
        
        return Observable.create(observer => {
            observer.next("Starting worker...");

            self.feedTasks()
                .flatMap((task) => self.executeTask(task))
                .map((result: TaskResult) => {
                    console.log("calculated, posting result");
                    console.log(result);
                    return result;
                })
                .flatMap((taskResult) => this.taskService.postTaskResult(taskResult))
                .map((result: boolean) => {
                    console.log("post result: " + result);
                    return result;
                })
                .subscribe(
                    result => {
                        console.log("subscribed result:" + result);
                        self.isBusy = false;
                    },
                    error => {
                        console.log("error while executing task");
                        console.log(error);
                        self.isBusy = false;
                    }
                );
        });
    }
Example #6
0
    /**
     * Read and return value from DB, given its key.
     * @param {string} key - the key of the vfalue we're reading
     */
    public getValue(key: string): any {
        let source: Observable<any> = Observable.create((observer) => {
            this.getStore(DICT_STORE, 'readonly').subscribe(
                (store: IDBObjectStore) => {
                    let index: IDBIndex = store.index('key'),
                        keyRange: IDBKeyRange = IDBKeyRange.only(key),
                        cursorRequest: IDBRequest = index.openCursor(keyRange);

                    cursorRequest.onsuccess = (event: ErrorEvent) => {
                        let cursor: IDBCursorWithValue = cursorRequest.result;
                        if (cursor) {
                            observer.next(cursor.value.value);
                            observer.complete();
                            // NB: don't call cursor.continue() because we
                            // expect only one value for key 'key'
                            // cursor.continue();
                        }
                        else {
                            observer.next(undefined);
                            observer.complete();
                        }
                    };
                    cursorRequest.onerror = (event: ErrorEvent) => {
                        observer.error('getValue():getStore(): cursor error');
                    };
                },
                (error) => {
                    observer.error('getValue(): ' + error);
                });
        });
        return source;
    }
Example #7
0
	open(el: ElementRef, text: string, align: string) {
		return Observable.create((observer: Observer<any>) => {
			// Resolve the TooltipComponent, and build it
			this._cr.resolveComponent(TooltipComponent).then((cmpFactory: ComponentFactory<TooltipComponent>) => {
				// Create reflective injector to provide an instance of TooltipData 
				let providers = ReflectiveInjector.resolve([
					{ provide: TooltipData, useValue: new TooltipData(el, text, align) },
				]);
				let injector = ReflectiveInjector.fromResolvedProviders(providers, this.viewContainer.parentInjector);

				// Create the component, outputs a promise...
				return this.viewContainer.createComponent(cmpFactory, this.viewContainer.length, injector);
			}).then((cmpRef: ComponentRef<TooltipComponent>) => {
				// Store reference to TooltipComponent
				this._toolTipCmp = cmpRef;

				// Append it to DOM
				this.viewContainer.element.nativeElement.appendChild(cmpRef.location.nativeElement);

				// Resolve the component
				observer.next(this._toolTipCmp);
				observer.complete();
			});
		});
	}
Example #8
0
    /**
     * Open the DB and set it up for use.
     * @returns {Observable<IDBDatabase>} Observable that emits the database
     * when it's ready for use.
     */
    private openDB(config: IdbConfig): Observable<IDBDatabase> {
        let source: Observable<IDBDatabase> = Observable.create((observer) => {
            let openRequest: IDBOpenDBRequest = indexedDB.open(
                config.name, config.version);

            openRequest.onsuccess = (event: Event) => {
                // console.log('indexedDB.open():onsuccess()');
                this.initStoreKeys(config.storeConfigs, openRequest, observer);
            };

            openRequest.onerror = (event: ErrorEvent) => {
                observer.error('openRequest.onerror');
            };

            openRequest.onblocked = (event: ErrorEvent) => {
                observer.error('openRequest.onblocked');
            };

            // This function is called when the database doesn't exist
            openRequest.onupgradeneeded = (event: IDBVersionChangeEvent) => {
                console.log('indexedDB.open():onupgradeended()');
                try {
                    this.createStores(config.storeConfigs, openRequest);
                }
                catch (error) {
                    observer.error('openRequest.onupgradeended: ' + error);
                }
            }; // openRequest.onupgradeneeded = ..
        });
        return source;
    }
	private handleHighResImageLoad(fullResImage){
		if (!fullResImage) {
			return;
		}

		const image = new Image();
		image.src = fullResImage;

		if (!image.complete) {
			const onLoadObservable = Observable.create(obs => {
				image.onload = () => {
					obs.next(image);
					obs.complete();
				}
			});

			// We want the animation to finish before replacing the pic
			// as the calculation has been done with the smaller image
			Observable.zip(onLoadObservable, this.didEnter)
				.subscribe(() => this.instance.updateImageSrcWithTransition(fullResImage));

		} else {
			this.instance.updateImageSrc(fullResImage)
		}
	}
Example #10
0
 /**
  * Stop recording
  * Precondition: called start() already
  * @returns {void}
  */
 public stop(): Observable<RecordingInfo> {
     console.log('WebAudioRecordWav:stop()');
     let obs: Observable<RecordingInfo> = Observable.create((observer) => {
         super.stop().subscribe(
             (recordingInfo: RecordingInfo) => {
                 const lastChunk: Int16Array = this.setter.activeBuffer
                     .subarray(0, this.setter.bufferIndex);
                 this.idb.createChunk(lastChunk).subscribe(
                     (key: number) => {
                         this.dbKeys.push(key);
                         console.log('saved final chunk: ' +
                             this.dbKeys.length + ', key: ' + key);
                         // update some essential components of data
                         // stored in db
                         recordingInfo.encoding = WAV_MIME_TYPE;
                         recordingInfo.size = recordingInfo.nSamples * 2;
                         recordingInfo.dbStartKey = this.dbKeys[0];
                         // reset db-keys, for the next recording
                         this.dbKeys = [];
                         // reset double buffer, for the next recording
                         this.setter.reset();
                         // return result now that db-save is done
                         observer.next(recordingInfo);
                         observer.complete();
                     });
             });
     });
     return obs;
 }
Example #11
0
    /**
     * Return all merged pull requests from server as an Observable
     * @param pullRequestsState: OPEN, MERGED or DECLINED
     */
    public fetchPullRequests(pullRequestsState: string): Observable<PullRequest[]> {
        return Observable.create((observer: Observer<PullRequest[]>) => {
            if (this.authService.getToken() != null) {
                let headers = new Headers();
                headers.append('Authorization', `Bearer ${this.authService.getToken()}`);
                this.http.get(
                    this.repoUrl + '/pullrequests?state=' + pullRequestsState + '&pagelen=50',
                    { headers: headers }
                )
                    .map(res => res.json())
                    .subscribe(prContainer => {
                        // get first page of pull requests
                        let pullRequests = prContainer.values;

                        // Calc number of other pages to get
                        let nbPages = Math.ceil(prContainer.size / prContainer.pagelen);

                        if (nbPages === 1) {
                            // Return the result to the observers
                            observer.next(pullRequests);
                        }

                        // Build array of fetch to subscribe
                        let fetchPages: any[] = [];
                        for (let i = 2; i <= nbPages; i++) {
                            fetchPages.push(this.fetchPullRequestPage(i));
                        }

                        // get synchrone result of all fetch
                        Observable.forkJoin(fetchPages).subscribe(datas => {
                            let dataArray: any = datas;
                            dataArray.forEach((data: any) => {
                                pullRequests = pullRequests.concat(data.values);
                            });

                            let modelPullRequests: PullRequest[] = pullRequests.map((pullRequest: any) => {

                                let modelPullRequest: PullRequest = {
                                    id: pullRequest.id,
                                    title: pullRequest.title,
                                    description: pullRequest.description,
                                    merge_commit: pullRequest.merge_commit,
                                    author: {userName: pullRequest.username,
                                             displayName: pullRequest.display_name,
                                             uuid: pullRequest.uuid},
                                    createdOn: new Date(pullRequest.created_on),
                                    updatedOn: new Date(pullRequest.updated_on),
                                    commentCount: pullRequest.comment_count
                                };
                                return modelPullRequest;
                            });
                            observer.next(modelPullRequests);
                        });

                    }, err => {
                        console.error('Failed to fetch PR:', err);
                    });
            }
        });
    }
Example #12
0
    public fetchPullRequestDiff(pullRequest: any): Observable<string> {


        return Observable.create((observer: Observer<any>) => {
            if (this.authService.getToken() != null) {
                let headers = new Headers();
                headers.append('Authorization', `Bearer ${this.authService.getToken()}`);

                if (!pullRequest.merge_commit) {
                    observer.error(new Error('Impossible to get PR diff from the API'));
                    observer.complete();
                } else {
                    this.http.get(this.repoUrl + '/diff/' + pullRequest.merge_commit.hash, { headers: headers })
                    .subscribe(
                        (diffResponse: any) => {
                            observer.next(diffResponse._body);
                            observer.complete();
                        },
                        err => {
                            observer.error(err);
                        }
                    );
                }
            } else {
                observer.error('no token');
            }
        });
    }
  login(username: string, password: string) {
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    let body = encodeDataPairs({grant_type: 'password', username: username, password: password});
    return Observable.create((observer:Observer<string>) => {
      this._http.post('http://dboesch.cloudapp.net/token', body, {headers: headers})
        .map(res => res.json())
        .subscribe(
          data => {
            console.log('token: ' + data.access_token);
            localStorage.setItem('access_token', data.access_token);
            observer.next('token');
          },
          error => {
            console.log('Authentication failed. Error: ' + error.text());
            observer.error('Authentication failed');
          },
          () => {
            console.log('Authentication complete.');
          }
        );
    });
  }
Example #14
0
  getEndangeredMamals() {

    return Observable.create(observer => {
      observer.next([new Species('Rhino', 'Mamal', 'Africa'), new Species('Tiger', 'Mamal', 'Africa'), new Species('Elephant', 'Mamal', 'Africa')]);
      observer.complete();
    });
  }
    dropDatabase(databaseName: string) {
        return Observable.create( (observer:Subscriber<any>) => {
            let deleteRequest: IDBOpenDBRequest = this.indexedDB.deleteDatabase(databaseName)
            
            var handleSuccess = (ev: Event) => {
                this.logEvent('dropDatabase', ev)
                if (ev.oldVersion > 0){
                    observer.next()
                    observer.complete()    
                } else {
                    observer.error(`Cannot find requested database '${databaseName}'`)
                }
            }
            var handleError = (ev: Event) => {
                this.logEvent('dropDatabase', ev)
                observer.error(ev.target.error)
            }
            var handleBlocked = (ev: Event) => {
                this.logEvent('dropDatabase', ev)
                observer.error(`Requested database '${databaseName}' is blocked`)
            }

            deleteRequest.addEventListener(IDB_EVENT_SUCCESS, handleSuccess)
            deleteRequest.addEventListener(IDB_EVENT_ERROR, handleError)
            deleteRequest.addEventListener(IDB_EVENT_BLOCKED, handleBlocked)
            return () => {
                deleteRequest.removeEventListener(IDB_EVENT_SUCCESS, handleSuccess)
                deleteRequest.removeEventListener(IDB_EVENT_ERROR, handleError)
                deleteRequest.removeEventListener(IDB_EVENT_BLOCKED, handleBlocked)
            }
        })
    }
Example #16
0
    /**
     * Read an item from a db store via its key
     * @param {string} storeName - the name of the db store from which
     * we're reading the item
     * @param {number} key - the item's key in the db store
     * @returns {Observable<T>} Observable that emits the item as
     * soon as the db read request completes
     */
    public read <T>(
        storeName: string,
        key: number
    ): Observable<T> {
        let source: Observable<T> = Observable.create((observer) => {
            if (isPositiveWholeNumber(key)) {
                this.getStore(storeName, 'readonly').subscribe(
                    (store: IDBObjectStore) => {
                        let getRequest: IDBRequest = store.get(key);

                        getRequest.onsuccess = (event: ErrorEvent) => {
                            // we return success even if not found
                            // but in that case return a falsy value
                            // otherwise return node on success
                            observer.next(getRequest.result);
                            observer.complete();
                        };

                        getRequest.onerror = (event: ErrorEvent) => {
                            observer.error('in getRequest.onerror');
                        };
                    },
                    (error) => {
                        observer.error('in getStore: ' + error);
                    }
                ); // this.getStore(storeName, 'readonly').subscribe(
            } // if (isPositiveWholeNumber(key)) {
            else {
                observer.error('invalid key: ' + key);
            }
        });
        return source;
    }
Example #17
0
    /**
     * Delete an item already in a db store from the store
     * @param {string} storeName - the name of the db store where the
     * existing item to delete is
     * @param {number} key - the key of the item to delete in the db store
     * @returns {Observable<void>} Observable that emits after delete ends
     */
    public delete(
        storeName: string,
        key: number
    ): Observable<void> {
        let source: Observable<void> = Observable.create((observer) => {
            if (isPositiveWholeNumber(key)) {
                this.getStore(storeName, 'readwrite').subscribe(
                    (store: IDBObjectStore) => {
                        let deleteRequest: IDBRequest = store.delete(key);

                        deleteRequest.onsuccess = (event: ErrorEvent) => {
                            observer.next();
                            observer.complete();
                        };

                        deleteRequest.onerror = (event: ErrorEvent) => {
                            observer.error('delete request');
                        };
                    },
                    (error) => {
                        observer.error(error);
                    }
                ); // this.getStore(storeName, 'readwrite').subscribe(
            } // if (isPositiveWholeNumber(key)) {
            else {
                observer.error('invalid key: ' + key);
            }
        });
        return source;
    }
 /**
  * Method to perform initial loading of the directory.
  * Calls prepare with the top community results.
  */
 loadDirectory() {
     if (this.store.directory.ready) {
         this.directory = Observable.create(observer => {
             this.store.directory.observer = observer;
             this.store.directory.observer.next(this.store.directory.context);
         });
     }
     else {
         if (!this.store.directory.loading) {
             this.store.directory.loading = true;
             this.dspaceService.fetchTopCommunities().subscribe(topCommunities => {
                 this.store.directory.context = this.prepare(null, topCommunities);
                 this.store.directory.observer.next(this.store.directory.context);
             },
             error => {
                 console.error('Error: ' + JSON.stringify(error, null, 4));
             },
             () => {
                 this.store.directory.ready = true;
                 this.store.directory.loading = false;
                 console.log('finished fetching top communities');
             });
         }
     }
 }
    getDownloadData(value: Observable<Object[]>) {
  return Observable.create(observer => {

        let xhr = new XMLHttpRequest();

        xhr.open('GET', `https://jsonplaceholder.typicode.com/posts`);
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.responseType='arraybuffer';

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {

                    var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    var blob = new Blob([xhr.response], { type: contentType });
                    observer.next(blob);
                    observer.complete();
                } else {
                    observer.error(xhr.response);
                }
            }
        }
        xhr.send();

    });

}
    upload(request: any, file: any, token: string): any {
        return Observable.create(observer => {
            let formData: FormData = new FormData();
            let xhr: XMLHttpRequest = new XMLHttpRequest();

            formData.append("uploads[]", file, file.name);

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    } else {
                        observer.error(xhr.response);
                    }
                }
            };

            xhr.open('POST', request.url, true);

            for(let header of request.headers) {
                xhr.setRequestHeader(header.key, header.value);
            }
            
            xhr.send(formData);
        });
    }
Example #21
0
    public getOrAddValue(key: string, value: any): Observable<any> {
        let source: Observable<any> = Observable.create((observer) => {
            // first we try to get the value
            this.getValue(key).subscribe(
                (dbValue: any) => {

                    if (isUndefined(dbValue)) {
                        // value isn't there, so add the (key, value) pair
                        console.log('getOrAddValue: NO! key: ' + key);
                        this.addKeyValue(key, value).subscribe(
                            (addedKey: number) => {
                                observer.next(value);
                                observer.complete();
                            },
                            (error) => {
                                observer.error('getOrAddValue():' +
                                    'addKeyValue(): ' + error);
                            });
                    }
                    else {
                        // value is there, return it
                        console.log('getOrAddValue: YES! key: ' + key);
                        observer.next(dbValue);
                        observer.complete();
                    }
                },
                (error) => {
                    observer.error('getOrAddValue():getValue(): ' + error);
                });
        });
        return source;
    }
Example #22
0
    /**
     * Obtains the geographic position, in terms of latitude and longitude coordinates, of the device.
     * @param {Object} [opts] An object literal to specify one or more of the following attributes and desired values:
     *   - enableHighAccuracy: Specify true to obtain the most accurate position possible, or false to optimize in favor of performance and power consumption.
     *   - timeout: An Integer value that indicates the time, in milliseconds, allowed for obtaining the position.
     *              If timeout is Infinity, (the default value) the location request will not time out.
     *              If timeout is zero (0) or negative, the results depend on the behavior of the location provider.
     *   - maximumAge: An Integer value indicating the maximum age, in milliseconds, of cached position information.
     *                 If maximumAge is non-zero, and a cached position that is no older than maximumAge is available, the cached position is used instead of obtaining an updated location.
     *                 If maximumAge is zero (0), watchPosition always tries to obtain an updated position, even if a cached position is already available.
     *                 If maximumAge is Infinity, any cached position is used, regardless of its age, and watchPosition only tries to obtain an updated position if no cached position data exists.
     * @returns {Observable} An observable sequence with the geographical location of the device running the client.
     */
    public getLocation(opts): Observable<any> {

        return Observable.create(observer => {

            if (window.navigator && window.navigator.geolocation) {
                window.navigator.geolocation.getCurrentPosition(
                    (position) => {
                        observer.next(position);
                        observer.complete();
                    },
                    (error) => {
                        switch (error.code) {
                            case 1:
                                observer.error(GEOLOCATION_ERRORS['errors.location.permissionDenied']);
                                break;
                            case 2:
                                observer.error(GEOLOCATION_ERRORS['errors.location.positionUnavailable']);
                                break;
                            case 3:
                                observer.error(GEOLOCATION_ERRORS['errors.location.timeout']);
                                break;
                        }
                    },
                    opts);
            }
            else {
                observer.error(GEOLOCATION_ERRORS['errors.location.unsupportedBrowser']);
            }

        });

    }
 public getCheckpointByKey(key: string): Observable<CheckpointModel> {
     return Observable.create(observer => {
         this.fireService.get('checkpoints/' + key).subscribe(toReturn => {
             observer.next(toReturn);   
         })
     })
 }
	private post(data:object)
	{		
		return Observable.create(observer =>
		{
			this.progressor.addLoading();
			
			var thing = this.http
				.post("StatisticsServlet", JSON.stringify(data))
				.map(res => res.json().data)
				.do(data =>
					{
						observer.next(data);
					},
					error =>
					{
						observer.error(error);
						this.progressor.removeLoading();
					},
					data =>
					{
						observer.complete();
						this.progressor.removeLoading();
					})
				.subscribe();
		});
	}
export default function analyticsService(
  connection,
  referenceDataService
): Object {
  const serviceClient = new ServiceClient(
    ServiceConst.AnalyticsServiceKey,
    connection
  )
  const positionsMapper = new PositionsMapper(referenceDataService)
  serviceClient.connect()
  return {
    get serviceStatusStream() {
      return serviceClient.serviceStatusStream
    },
    getAnalyticsStream(analyticsRequest) {
      Guard.isDefined(analyticsRequest, 'analyticsRequest required')
      return Observable.create(o => {
        log.debug('Subscribing to analytics stream')

        return serviceClient
          .createStreamOperation('getAnalytics', analyticsRequest)
          .retryWithPolicy(
            RetryPolicy.backoffTo10SecondsMax,
            'getAnalytics',
            Scheduler.async
          )
          .map(dto => positionsMapper.mapFromDto(dto))
          .subscribe(o)
      })
    }
  }
}
    constructor (private _ngZone : NgZone) {
       //this.db = new PouchDB('http://127.0.0.1:5984/githubnotes');

        this.db = new PouchDB('githubnotes');

        this.db.replicate.from('http://127.0.0.1:5984/githubnotes', {live: true, retry: true});
        this.db.replicate.to('http://127.0.0.1:5984/githubnotes', {live: true, retry: true});

        var ddoc = {
            _id: '_design/notes',
            views: {
                notes: {
                    map: function(doc) {
                        if (doc.type === 'note') {
                            emit([doc.username, doc.date], doc );
                        }
                    }.toString()
                }
            }
        };

        this.db.put(ddoc).catch(err => {});

        const _changesStream = this.db.changes({live: true, include_docs: true, since: 'now'});

        this.notesstream = Observable.create(observer => {
            _changesStream.on('change', (change) => { this._ngZone.run ( () => observer.next(change) ); });
            _changesStream.on('complete', (info) => { this._ngZone.run ( () => observer.complete()); });
            _changesStream.on('error', (error) => { this._ngZone.run ( () => observer.error(error)); });
        }).share();
    }
  makeFileRequest(url: string, params: string[], files: any[]): Observable<any> {
    return Observable.create((observer: Observer<any>) => {
      let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();

      var test = window.location.pathname.split('/').length - 1;
      var id = window.location.pathname.split('/')[test];

      for (let i = 0; i < files.length; i++) {
        formData.append(id, files[i], files[i].Title);
      }

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            observer.next("test");
            observer.complete();
          } else {
            observer.error(xhr.response);
          }
        }
      };

      xhr.open('POST', url, true);
      xhr.send(formData);
    });
  }
  public makeFileRequest (url: string, params: string[], files: File[]): Observable<number> {
    return Observable.create( (observer:Observer<String>) => {
      let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();


      formData.append("file", files[0], files[0].name);
      formData.append("naam", "TEST");

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            observer.next(JSON.parse(xhr.response));
            observer.complete();
          } else {
            observer.error(xhr.response);
          }
        }
      };

      xhr.upload.onprogress = (event) => {
        var progress = Math.round(event.loaded / event.total * 100);

        this.progressObserver.next(progress);
      };

      xhr.open('POST', url, true);
      xhr.send(formData);
    });
  }
const createBlotterService = (connection) => {
  const serviceClient = new ServiceClient(ServiceConst.BlotterServiceKey, connection)
  const tradeMapper = new TradeMapper()
  serviceClient.connect()
  return {
    get serviceStatusStream() {
      return serviceClient.serviceStatusStream
    },

    getTradesStream() {
      return Observable.create(o => {
        log.debug('Subscribing to trade stream')
        return serviceClient
          .createStreamOperation('getTradesStream', {
            /* noop request */
          })
          .retryWithPolicy(
            RetryPolicy.backoffTo10SecondsMax,
            'getTradesStream',
            Scheduler.async
          )
          .map(dto => tradeMapper.mapFromDto(dto))
          .subscribe(o)
      })
    }
  }
}
    /**
     * list()
     * 
     */
    list(db:IDBDatabase, storeName:string){
        return Observable.create( (observer:Subscriber<any>) => {
            let tnx: IDBTransaction = this.getTransaction(db, storeName, "readonly")
            let store: IDBObjectStore = this.getObjectStore(tnx, storeName)

            let cursor: IDBRequest = store.openCursor()
            
            

            var onSuccess = (ev:Event) => {
                this.logEvent('listCursor', ev)
                let iterator: IDBCursorWithValue = ev.target.result;
                if (iterator) {
                    observer.next(iterator.value);
                    iterator.continue();
                } else {
                    observer.complete()
                }
            }
            
            var onError = (ev:Event) => {
                this.logEvent('listCursor', ev)
                observer.error(ev.target.error)
            }
            
            cursor.addEventListener(IDB_EVENT_SUCCESS, onSuccess)
            cursor.addEventListener(IDB_EVENT_ERROR, onError)
            
            return () => {
                cursor.removeEventListener(IDB_EVENT_SUCCESS, onSuccess)
                cursor.removeEventListener(IDB_EVENT_ERROR, onError)
            }
                
        })
    }