當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。