Angular中的数据请求 内置模块HttpClient实现(get post jsonp 以及第三方模板axios请求数据

封装服务:

httpservice.service.ts

import { Injectable } from '@angular/core';
import axios from "axios";
@Injectable({
  providedIn: 'root'
})
export class HttpserviceService {

  constructor() { }
  axiosGet(api){
    return new Promise((resolve,reject)=>{
      axios.get(api).then(function(response){
        resolve(response)
      });
    });
  }
}

在app.module.ts中使用:

import{HttpserviceService}from "./services/httpservice.service";

providers: [HttpserviceService],

2.

app.module.ts

//引入HttpClientModule
import{HttpClientModule,HttpClientJsonpModule}from "@angular/common/http";

  imports: [
    HttpClientModule,
    HttpClientJsonpModule
  ],

 

http.component.ts

import { Component, OnInit } from '@angular/core';
//当作一个服务:
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { from } from 'rxjs';


//使用服务里面的axios获取数据:
import{HttpserviceService} from "../../services/httpservice.service";
@Component({
  selector: 'app-http',
  templateUrl: './http.component.html',
  styleUrls: ['./http.component.scss']
})
export class HttpComponent implements OnInit {
  public list: any[] = [];
  constructor(public http: HttpClient,public httpService:HttpserviceService) { }

  ngOnInit() {
  }
  getData() {
    alert("执行get请求");
    let api = "http://a.itying.com/api/productlist";
    this.http.get(api).subscribe((response: any) => {
      console.log(response);
      this.list = response.result;
    })
  }

  doLogin() {
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }
    //存在跨域:
    var api = "";
    this.http.post(api, { "username": "张三", "age": 20 }, httpOptions).subscribe((response) => {

    });
    alert("执行");
  }

  getJsonpData() {

    //jsonp请求,服务器必须的支持jsonp:

    let api = "http://a.itying.com/api/productlist";
    this.http.jsonp(api, 'callback').subscribe((response)=>{
      console.log(response);
    });
  }

  getAxiosData(){
    let api = "http://a.itying.com/api/productlist";
    this.httpService.axiosGet(api).then((data)=>{
      console.log(data);
    });
  }
}

http.component.html

<p>
    new works
</p>
<button (click)="getData()">get请求的数据</button>

<br/>
<ul>
    <li *ngFor="let item of list">
        {{item.title}}
    </li>
</ul>

<br/>
<button (click)="doLogin()">post提交数据</button>

<br/>
<button (click)="getJsonpData()">jsonp请求</button>

<br/>
<button (click)="getJsonpData()">通过第三方模块获取的请求的数据</button>

 

 

posted @ 2020-01-09 23:28  生如逆旅,一苇以航  阅读(503)  评论(0编辑  收藏  举报