Angular数据交互(get、post)与axios

Angular的数据交互get请求:

定义服务,引入axios

import axios from 'axios';

import { Observable } from 'rxjs';

提供get方法,通过observable处理相应结果:

    getData(url){

    return new Observable((observable)=>{

      axios.get(url).then(function(response){

        observable.next(response);

      })   

    })

}

组件中的业务:

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

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

import {HttpclientService} from '../../services/httpclient.service'

@Component({

  selector: 'app-news',

  templateUrl: './news.component.html',

  styleUrls: ['./news.component.scss']

})

export class NewsComponent implements OnInit {

  /*angular的数据交互

  1.  在app.module.ts引入httpclientmodule并声明import {HttpClientModule} from '@angular/common/http'

  2.  在使用的组件业务中引入 httpclient import {HttpClient} from '@angular/common/http'

  3. 在构造器实例化 http    public http:HttpClient

  4.通过 this调用

*/

/*

    post

    引入 httpclient之后,需要引入 httpheaders

*/

  constructor(public http:HttpClient,public httpclientAxios:HttpclientService) { }

  public list:any[]=[];

  public resultPost:any="";

  ngOnInit(): void {

  }

  getData(){

      let url:any="http://localhost:8080/TestAngular/angular/test";

      this.http.get(url).subscribe((response:any)=>{

        console.log(response);

       this.list=response;

      })

      } 

  doPost(){

      //定义一个请求头

      const httpOptions={headers:new HttpHeaders({'Content-Type':'application/json'})}

      let url:any="http://localhost:8080/TestAngular/angular/testpost";

      this.http.post(url,{'name':'testname','phone':"123456 "},httpOptions).subscribe((response:any)=>{

        console.log(response);  

        this.resultPost=response;

      })

  }

  /*使用jsonp可以避免跨越

  1. 在app.module.ts中还要引入 httpclientjsonpmodule,并声明

  2. 前提是服务器支持jsonp

  "http://localhost:8080/TestAngular/angular/test?callback=xxx"

  */ 

  getJsonp(){

    let url:any="http://localhost:8080/TestAngular/angular/test";

    this.http.jsonp(url,'callback').subscribe((response:any)=>{

         this.list=response;

    })

  }

  /**axios

   * 

   * 1.安装  cnpm install axios --save

   * 2. 引入 import axios from 'axios'

   * 3.  在通过rxjs promise 处理axios的异步结果

   */

  getByAxios(){

    let url:any="http://localhost:8080/TestAngular/angular/test";

      this.httpclientAxios.getData(url).subscribe((response:any)=>{

        console.log(response);

        this.list=response.data;

      })

  }

}

你可能感兴趣的:(Angular数据交互(get、post)与axios)