Angular入门教程 | 06Angular数据请求

326 阅读2分钟

在Angular5.x之后get和post与服务器交互使用的是HttpClientModule模块。

1.在app.module.ts中引入 HttpClientModule模块,并注入

import {HttpClientModule} from '@angular/common/http';
imports:[
    BrowserModule,
    HttpClientModule
]

2.在用到的地方引入HttpClient并在构造函数声明

import {HttpClient} from '@angular/common/http';

constructor(public http:HttpClient) { }

3.get请求

var api = 'http://a.itying.com/api/productlist';
this.http.get(api).subscribe(response=>{
    console.log(response)
})

4.post请求

post请求大体上和get请求一样,只不过post请求需要你指定请求头类型,所以需要你额外引入HttpHeaders

import {HttpClient , HttpHeaders} from '@angular/common/http';
//然后在之后http.post的时候需要把类型给他传进去
const httpOptions = {
    headers:new HttpHeaders({'Content-Type':'application/json'})
};
var api = 'http://127.0.0.1:3000/doLogin'
this.http.post(api,{username:'章三',age:'20'},httpOptions).subscribe(response=>{
    console.log(response)
})

发起 JSONP 请求

当服务器不支持 CORS 协议时,应用程序可以使用 HttpClient 跨域发出 JSONP 请求。

Angular 的 JSONP 请求会返回一个 Observable。 遵循订阅可观察对象变量的模式,并在使用 async 管道管理结果之前,使用 RxJS map 操作符转换响应。

在 Angular 中,通过在 NgModule 的 imports 中包含 HttpClientJsonpModule 来使用 JSONP。

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-get-data',
  templateUrl: './get-data.component.html',
  styleUrls: ['./get-data.component.scss']
})
export class GetDataComponent implements OnInit {

  constructor(public http: HttpClient) { }

  public arr: any = []
  ngOnInit(): void {
  }
  getJsonpData() {
    var api = 'http://a.itying.com/api/productlist'

    // alert('getJsonp')
    this.http.jsonp(api, 'callback').subscribe((res) => {
      console.log(res, 'gogogogo');
    })
  }

该请求将 heroesURL 作为第一个参数,并将回调函数名称作为第二个参数。响应被包装在回调函数中,该函数接受 JSONP 方法返回的可观察对象,并将它们通过管道传给错误处理程序。

使用第三方模块Axios来实现请求数据

首先需要我们安装axios 使用 npm:

 npm install axios

在angular里面,哪个组件要发请求就在哪个组件通过import引入

import axios from axios

在这里我单独对axios做了一个二次封装,我们先创建一个service,然后在这个里面做封装httpService.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)
        })
        .catch(function (error) {
          console.log(error);
        });
    })

  }
}

之后需要在app.module.ts里面引入这个服务,并且在provider里面配置好,这个时候我们就可以在组件里直接使用了。我在news.component.ts里面引入封装好的axios然后请求接口

import { Component, OnInit } from '@angular/core';

// 1.引入服务
import { HttpServiceService } from '../../services/http-service.service'

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {

  ngOnInit(): void {
  }
  //2.声明服务
  constructor(public HttpService: HttpServiceService) { }
  ngAfterViewInit(): void {
  }
  //3.使用服务
  axiosGetData() {
    var api = 'http://a.itying.com/api/productlist'
    //因为封装的时候是通过axios的方法,所以这里调用的.then
    this.HttpService.axiosGet(api).then((data) => {
      console.log(data, 'axios获取data');

    })
  }
}