Home >Web Front-end >JS Tutorial >Example practice of angular5 httpclient

Example practice of angular5 httpclient

亚连
亚连Original
2018-05-30 17:41:311773browse

This article mainly introduces the practical examples of angular5 httpclient. Now I will share it with you and give you a reference.

Httpclient has been used since angular 4.3.0 and later, replacing the previous http, and the referenced package path has changed to angular/common/http

A basic httpclient example

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HttpDefaultOptions } from './http.default.options';

@Injectable()
export class Service {

 private static METHOD_DELTE = 'DELETE';
 private static METHOD_POST = 'POST';
 private static METHOD_GET = 'GET';
 private static METHOD_PUT = 'PUT';

 constructor(private httpClient: HttpClient) {
 }

 /**
  * 将数据上传
  * @param data
  * @param {Function} func
  */
 uploadDataPost(data: any, func: Function) {
  let url = '/api/test';
  this.apiPost(url, data)
   .subscribe((response: HttpResponse) => {
    func(response);
   }, error => {
    func(undefined);
   });
 }

 /**
  * 返回json 格式的obj 对象
  * @param url
  * @param body
  * @param urlSearchParams
  * @returns {Observable<{}>}
  */
 apiPost(url, body, urlSearchParams?: any): Observable<{}> {
  let options = {
   body: body ? body : null,
   params: urlSearchParams,
   responseType: &#39;json&#39;
  };
  return this.httpClient.request(Service.METHOD_POST, url, options);
 }

 /**
  * 返回一个obj 对象
  * @param url
  * @param urlSearchParams url 的查询参数
  * @returns {Observable<{}>}
  */
 apiGet(url, urlSearchParams?: any): Observable<{}> {
  let options = {
   params: urlSearchParams,
   responseType: &#39;json&#39;
  };
  return this.httpClient.request(Service.METHOD_GET, url, options);
 }
}

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed explanation of Vue custom dynamic component instances

Introduction to time-sharing functions for javascript performance optimization

E-mail address format verification in JavaScript

The above is the detailed content of Example practice of angular5 httpclient. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn