Ejemplo n.º 1
0
    /**
     * Send the a http request the the given path.
     * Optionally accepts a request body.
     *
     * @param path the target path, usually starting with /rest
     * @param method the required HTTP method (i.e get, post, put)
     * @param data optional, if sending a data body is required
     * @param queryParams optional queryparams to append to the path
     * @param customHeader optional custom HTTP header of required
     * @param responseType optional response type, default set to json (i.e 'arraybuffer')
     * @returns a promise containing a generic
     */
    private async send<T>(
        path: string,
        method: HTTPMethod,
        data?: any,
        queryParams?: QueryParams,
        customHeader?: HttpHeaders,
        responseType?: string
    ): Promise<T> {
        // end early, if we are in history mode
        if (this.OSStatus.isInHistoryMode && method !== HTTPMethod.GET) {
            throw this.handleError('You cannot make changes while in history mode');
        }

        // there is a current bug with the responseType.
        // https://github.com/angular/angular/issues/18586
        // castting it to 'json' allows the usage of the current array
        if (!responseType) {
            responseType = 'json';
        }

        const url = path + formatQueryParams(queryParams);
        const options = {
            body: data,
            headers: customHeader ? customHeader : this.defaultHeaders,
            responseType: responseType as 'json'
        };

        try {
            return await this.http.request<T>(method, url, options).toPromise();
        } catch (e) {
            throw this.handleError(e);
        }
    }
    transmit(request: KalturaMultiRequest,  clientOptions: KalturaClientOptions, defaultRequestOptions: KalturaRequestOptions): Observable<KalturaMultiResponse> {

        const parameters = prepareParameters(request, clientOptions, defaultRequestOptions);

        const endpointUrl = createEndpoint(request, clientOptions, parameters['service'], parameters['action']);
        delete parameters['service'];
        delete parameters['action'];



        return this._http.request('post', endpointUrl,
            {
                body: parameters,
                headers: getHeaders()
            }).pipe(
            catchError(
                error => {
                    const errorMessage = error instanceof Error ? error.message : typeof error === 'string' ? error : null;
                    throw new KalturaClientException("client::multi-request-network-error", errorMessage || 'Error connecting to server');
                }
            ),
            map(
                result => {
                    try {
                        return request.handleResponse(result);
                    } catch (error) {
                        if (error instanceof KalturaClientException || error instanceof KalturaAPIException) {
                            throw error;
                        } else {
                            const errorMessage = error instanceof Error ? error.message : typeof error === 'string' ? error : null;
                            throw new KalturaClientException('client::multi-response-unknown-error', errorMessage || 'Failed to parse response');
                        }
                    }
                }));
    }
Ejemplo n.º 3
0
  upload(file: File) {
    if (!file) { return; }

    // COULD HAVE WRITTEN:
    // return this.http.post('/upload/file', file, {
    //   reportProgress: true,
    //   observe: 'events'
    // }).pipe(

    // Create the request object that POSTs the file to an upload endpoint.
    // The `reportProgress` option tells HttpClient to listen and return
    // XHR progress events.
    const req = new HttpRequest('POST', '/upload/file', file, {
      reportProgress: true
    });

    // The `HttpClient.request` API produces a raw event stream
    // which includes start (sent), progress, and response events.
    return this.http.request(req).pipe(
      map(event => this.getEventMessage(event, file)),
      tap(message => this.showProgress(message)),
      last(), // return last (completed) message to caller
      catchError(this.handleError(file))
    );
  }
Ejemplo n.º 4
0
    uploadFile(dataSetId: string, file: File): Observable<HttpEvent<DataSetFile>> {
        const formData = new FormData();
        formData.append("file", file, file.name);

        const request = new HttpRequest("POST", FileManagerService.getUploadsUrl(dataSetId), formData, {reportProgress: true});
        return this.http.request<DataSetFile>(request);
    }
Ejemplo n.º 5
0
    public send<TContent>(request: ApiRequest): Observable<ApiResponse<TContent>> {

        let options = this.buildOptions(request);

        let url = '/';
        if (this.baseAddress.endsWith('/') || request.requestUri.startsWith('/')) {
            url = '';
        }

        url = this.baseAddress + url + request.requestUri;

        return this.http.request<HttpResponse<TContent>>(request.method, url, options)
            .pipe(              
                map((response: HttpResponse<TContent>) => {
                    let apiResponse = new ApiResponse<TContent>(response);
                    return apiResponse;
                }),
                
                catchError((err, caught) => {

                    if (err.status === 401) {
                        return this.handleUnAuthorizedError<TContent>(err, url, request);
                    } else if(err.status === 403) {
                        return this.handleForbiddenError<TContent>();
                    }

                    return new Observable<ApiResponse<TContent>>();
                })

                
            );
    }
Ejemplo n.º 6
0
	// ---
	// PUBLIC METHODS.
	// ---

	// I make an HTTP request to the API and return an observable response.
	public makeRequest<T>( requestConfig: RequestConfig ) : Observable<T> {

		// The point of having a specialized API HttpClient is that you can bake-in logic
		// that is specific to this API, but not necessarily needed for any other
		// HttpClient in the application. There is a LOT you can do with this pattern;
		// but, for the PURPOSES OF THIS DEMO, we're only going to be sending the current
		// browser's timezone offset (in minutes).
		var headers: StringMap = {
			...requestConfig.headers,

			// Pass the timezone offset as a special HTTP header. This way, the server
			// can record this value if it has been changed (based on the user's locale).
			"X-Timezone-Offset": this.getTimezoneOffset()
		};

		var httpStream = this.httpClient.request<T>(
			requestConfig.method,
			requestConfig.url,
			{
				responseType: "json",
				headers: headers
			}
		);

		return( httpStream );

	}
Ejemplo n.º 7
0
 public delete(url, params) : Observable<any> {
   return this.http.request('DELETE', url, {
     body: params
   })
   .map(this.success)
   .catch(this.error);
 }
Ejemplo n.º 8
0
 streamPost(url: string, body: any): Observable<any> {
   const resultSubject = new Subject<any>();
   const request = new HttpRequest('POST', url, body, {
     responseType: 'text',
     reportProgress: true,
   });
   let lastSeq = -1;
   this.http.request(request).subscribe(
     (event: HttpEvent<any>) => {
       if (event.type != HttpEventType.DownloadProgress) return;
       let text = (event as HttpDownloadProgressEvent).partialText || '';
       if (text.startsWith('[')) {
         text = text.slice(1);
       }
       if (text.endsWith(']')) {
         text = text.slice(0, -1);
       }
       if (text.endsWith(',')) {
         text = text.slice(0, -1);
       }
       const msgs = JSON.parse('[' + text + ']');
       for (const msg of msgs) {
         if (lastSeq < msg['seq']) {
           resultSubject.next(msg);
           if (msg['done']) resultSubject.complete();
           lastSeq = msg['seq'];
         }
       }
     },
     error => {
       resultSubject.error(error);
     }
   );
   return resultSubject;
 }
Ejemplo n.º 9
0
  uploadCities(data: string): Observable<HttpEvent<any>> {
    const req = new HttpRequest('POST', '/api/cities/uploads', data, {
      reportProgress: true,
    });

    return this.http.request(req);
  }
Ejemplo n.º 10
0
 upload(path: string, file: File): Observable<any> {
   const req: HttpRequest<{}> = new HttpRequest('POST', path, file, {
     headers: this.headers,
     reportProgress: true,
     withCredentials: this.withCredentials,
   })
   return this.http.request(req)
 }
Ejemplo n.º 11
0
  create(personId: number, file: File): Observable<HttpEvent<any>> {
    const formData = new FormData();
    formData.append('file', file);

    const req = new HttpRequest('POST', `/api/persons/${personId}/files`, formData, {
      reportProgress: true,
    });

    return this.http.request(req);
  }
Ejemplo n.º 12
0
 public getBundle(url, params): Observable<any> {
   const req = new HttpRequest('GET', url, {
     reportProgress: true, responseType: 'blob'
   });
   // const req = new HttpRequest('GET', url, {
   //   responseType: 'blob'
   // });
   return this.http.request(req);
   // return this.http.get('https://s3.amazonaws.com/nist-midas/1858/20170213_PowderPlate2_Pad.zip',  {responseType: 'blob'});
 }
  storeRecipes() {
    // const headers = new HttpHeaders().set('Authorization', 'Bearer afdklasflaldf');

    // return this.httpClient.put('https://ng-recipe-book-3adbb.firebaseio.com/recipes.json', this.recipeService.getRecipes(), {
    //   observe: 'body',
    //   params: new HttpParams().set('auth', token)
    //   // headers: headers
    // });
    const req = new HttpRequest('PUT', 'https://ng-recipe-book-3adbb.firebaseio.com/recipes.json', this.recipeService.getRecipes(), {reportProgress: true});
    return this.httpClient.request(req);
  }
 storeRecipes() {
   // return this.http.put('https://angular-http-test-60147.firebaseio.com/recipes.json', this.recipeService.getRecipes(),
   //   {
   //     observe: 'body',
   //     params: new HttpParams().set('auth', token)
   //     // headers: headers
   //   });
   const req = new HttpRequest('PUT', 'https://angular-http-test-60147.firebaseio.com/recipes.json', this.recipeService.getRecipes());
     // {reportProgress: true, params: new HttpParams().set('auth', token)}
   return this.http.request(req);
 }
Ejemplo n.º 15
0
    public send<TContent>(request: ApiRequest): Observable<ApiResponse<TContent>> {

        let options = this.buildOptions(request);

        let url = this.baseAddress + '/' + request.requestUri;

        return this.http.request<TContent>(request.method, url, options)
            .map((response: TContent) => {
               let apiResponse = new ApiResponse<TContent>(response);
               return apiResponse;
            });
    }
Ejemplo n.º 16
0
storeRecipes(){
    const token=this.authService.getToken();
    // return this.httpClient.put('https://ng-recipe-book-1f94f.firebaseio.com/recipes.json',
    //        this.recipeService.getRecipes(),{
    //            observe:'body',
    //            params:new HttpParams().set('auth',token)
    //        });
    const req=new HttpRequest('PUT','https://ng-recipe-book-1f94f.firebaseio.com/recipes.json',
this.recipeService.getRecipes(),{
    reportProgress:true,params:new HttpParams().set('auth',token)})
   return this.httpClient.request(req);
}
Ejemplo n.º 17
0
  private request(url: string, method: string, body?: any): Observable<any> {
    const token: string = this._auth.token ? this._auth.token : '';
    const h: HttpHeaders = new HttpHeaders()
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Authorization', `Bearer ${token}`);
    // .set('Client', client );
    const options: any = {
      body: body,
      headers: h,
      withCredentials: true
    };

    return this._http.request<any>(method, '/api/' + url, options);
  }
Ejemplo n.º 18
0
 public sendRequest(payload: any): Observable<any> {
   const parameters = Object.assign({},
     {
       method: 'GET',
       url: 'api/',
       options: {}
     },payload);
   console.log(parameters);
   return this.http.request<any>(
     parameters.method,
     parameters.url,
     parameters.options
   );
 }
Ejemplo n.º 19
0
    storeRecipes() {
        // const headers = new HttpHeaders().set('Authorization','jfiHlkLKHHlklLKAFJI18YR98');
        // return this.httpClient.put('https://udemy-rec.firebaseio.com/recipes.json',
        //     this.recipeServices.getRecipes(),{
        //         observe:'body',
        //         params: new HttpParams().set('auth',token)
        //         // headers: headers
        //     });

        const req = new HttpRequest('PUT','https://udemy-rec.firebaseio.com/recipes.json', 
            this.recipeServices.getRecipes(),
            {reportProgress:true});
        return this.httpClient.request(req);
    }
Ejemplo n.º 20
0
            this.authHandler(authUrl).subscribe((authResult) => {
    
                // If the user was able to authenticate, retry the request.
                let options = this.buildOptions(request);

                this.http.request<HttpResponse<TContent>>(request.method, url, options)
                    .pipe(              
                        map((response: HttpResponse<TContent>) => {
                            let apiResponse = new ApiResponse<TContent>(response);
                            return apiResponse;
                        })
                    ).subscribe(
                        (resp: ApiResponse<TContent>) => o.next(resp)
                    ); 
                }
Ejemplo n.º 21
0
    public send<TContent>(request: ApiRequest): Observable<ApiResponse<TContent>> {

        let options = this.buildOptions(request);

        let url = '/';
        if (this.baseAddress.endsWith('/') || request.requestUri.startsWith('/')) {
            url = '';
        }

        url = this.baseAddress + url + request.requestUri;

        return this.http.request<TContent>(request.method, url, options)
            .map((response: any) => {
               let apiResponse = new ApiResponse<TContent>(response);
               return apiResponse;
            });
    }
Ejemplo n.º 22
0
    uploadForm(event): Observable<any> {

        // console.log("uplodaForm");
        if (event === void 0 || event.target === void 0 || event.target.files === void 0) {
            return ObservableThrow(new Error('file_is_not_selected'));
        }

        const files = event.target.files;
        if (files === void 0 || files[0] === void 0 || !files[0]) {
            return ObservableThrow(new Error('file_is_not_selected_or_file_does_not_exist'));
        }
        const file = files[0];

        const formData = new FormData();
        formData.append('userfile', file, file.name);
        formData.append('route', 'file.upload');
        formData.append('session_id', this.user.sessionId);

        // console.log("url: ", this.x.getServerUrl());
        // console.log("data: ", formData);
        const req = new HttpRequest('POST', this.x.getServerUrl(), formData, {
            reportProgress: true,
            responseType: 'json'
        });

        return this.http.request(req)
            .map(e => {
                if (e instanceof HttpResponse) { // success event.
                    if ( e.status === 200 ) {
                        if ( e.body && e.body['code'] === 0) {
                            return e.body['data'];
                        } else {
                            return e.body; // Return Wordpress Xapi Server error
                        }
                    }
                } else if ( e instanceof HttpHeaderResponse ) { // header event
                    return {};
                } else if (e.type === HttpEventType.UploadProgress) { // progress event
                    return Math.round(100 * e.loaded / e.total);
                }
                return e; // other events
            });

    }
Ejemplo n.º 23
0
    private request(url: string, method: string, body?: any, params?: any, responseType?: any): Observable<Object> {
        const headers = new HttpHeaders();

        try {
            const requestOptions = {
                body: body,
                headers: headers,
                params: params
            };
            if (responseType) {
                requestOptions['responseType'] = responseType;
            }
            // if (environment.withCredentials) {
            //     requestOptions['withCredentials'] = true;
            // }

            return this.http.request(method, url, requestOptions);
        }
        catch (error) {
            return Observable.throw(error);
        }

    }
 deleteComponentInventory(json) {
 	return this.http.request('delete', 'http://localhost:3000/api/componentInventory/', {body : json});
 }
 startJob(json) {
 	return this.http.request('post','http://localhost:3000/api/sendOut/', {body : json} );
 }
 finishJob(json) {
 	return this.http.request('put', 'http://localhost:3000/api/logReturn/', {body : json} );
 }
Ejemplo n.º 27
0
 deleteImage(source: string): Observable<string> {
     return this.http.request<string>('delete', `${environment.URL}/images`, { body: { src: source } });
 }
Ejemplo n.º 28
0
 deleteIndex(id: string): Observable<HttpResponse<void>> {
   return this.http.request<void>('DELETE', this.configuration.backendUrl + '/indices', {body: {id: id}, observe: 'response'});
   // .map(response => response.status);
 }
Ejemplo n.º 29
0
 request(method: string, url: string, data: object, options: object): Observable<any> {
     const req = new HttpRequest(method, this.url(url), data, options);
     return this.http.request(req);
 }
Ejemplo n.º 30
0
  //上传一个video
  uploadVideo(event) {
    if (this.classId === "") {
      this.videoInputEle.nativeElement.value = "";
      let alert = this.alertCtrl.create({
        title: 'Ops',
        subTitle: 'please choose a classId',
        buttons: ['OK'],
      });
      alert.present();
      return;

    } else {
      //在browser上进行上传
      let formDatat = new FormData();
      formDatat.append("files", event.target.files[0], event.target.files[0].name);
      formDatat.append("classId", this.classId);
      formDatat.append("name", this.name);
      let httpRequest = new HttpRequest("POST", URL_path.class.uploadVideo, formDatat, { reportProgress: true });
      let loading = this.loadingCtrl.create({
        content: 'Please wait...'
      });
      
      this.http.request(httpRequest).subscribe(
        (event:any) => {
          console.log(event.type)
          if(event.type == 0){
              //为0,开始上传
              loading.present();              
          }
          if (event.type === HttpEventType.UploadProgress) {
            console.log("Upload progress event", event);
             loading.setContent("already upload:"+((event.loaded/event.total)*100).toFixed(2)+"%");
          }
          if (event.type === HttpEventType.Response) {
            console.log("response received...", event.body);

              let alert = this.alertCtrl.create({
                title: 'Ops',
                subTitle:event.body.des,
                buttons: ['OK'],
              });
              alert.present().then(()=>{
                if(event.body.result === false){
                    //失败了,清空下
    
                    this.videoInputEle.nativeElement.value = "";

                }else {
                  this.navCtrl.pop();//成功了
                }
              });
              loading.dismiss();
          }
        },
        (error) => {
          let alert = this.alertCtrl.create({
            title: 'Ops',
            subTitle: error.message,
            buttons: ['OK'],
          });
          alert.present();
        },
        () => {

        })


    }

  }