当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript HttpClient.request方法代码示例

本文整理汇总了TypeScript中@angular/common/http.HttpClient.request方法的典型用法代码示例。如果您正苦于以下问题:TypeScript HttpClient.request方法的具体用法?TypeScript HttpClient.request怎么用?TypeScript HttpClient.request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在@angular/common/http.HttpClient的用法示例。


在下文中一共展示了HttpClient.request方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: formatQueryParams

    /**
     * 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);
        }
    }
开发者ID:FinnStutzenstein,项目名称:OpenSlides,代码行数:45,代码来源:http.service.ts

示例2: transmit

    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');
                        }
                    }
                }));
    }
开发者ID:kaltura,项目名称:clients-generator,代码行数:35,代码来源:kaltura-multi-request-adapter.ts

示例3: upload

  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))
    );
  }
开发者ID:iproduct,项目名称:course-angular,代码行数:25,代码来源:uploader.service.ts

示例4: uploadFile

    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);
    }
开发者ID:prashanthc97,项目名称:kylo,代码行数:7,代码来源:file-manager.service.ts

示例5: map

    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>>();
                })

                
            );
    }
开发者ID:grecosoft,项目名称:Sandbox,代码行数:32,代码来源:ApiClient.ts

示例6:

	// ---
	// 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 );

	}
开发者ID:bennadel,项目名称:JavaScript-Demos,代码行数:32,代码来源:api.http-client.ts

示例7: delete

 public delete(url, params) : Observable<any> {
   return this.http.request('DELETE', url, {
     body: params
   })
   .map(this.success)
   .catch(this.error);
 }
开发者ID:SrTristao,项目名称:avisemeapp,代码行数:7,代码来源:http.service.ts

示例8: streamPost

 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;
 }
开发者ID:wzong,项目名称:TinyCloud,代码行数:35,代码来源:streaming.ts

示例9: uploadCities

  uploadCities(data: string): Observable<HttpEvent<any>> {
    const req = new HttpRequest('POST', '/api/cities/uploads', data, {
      reportProgress: true,
    });

    return this.http.request(req);
  }
开发者ID:Ninja-Squad,项目名称:globe42,代码行数:7,代码来源:search-city.service.ts

示例10: upload

 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)
 }
开发者ID:weiwang94,项目名称:element-angular,代码行数:8,代码来源:upload.request.ts


注:本文中的@angular/common/http.HttpClient.request方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。