Angular中的数据交互(get post jsonp)

一、get请求

Angular5.x以后get、post和服务器交互使用的是HTTPClientModule模块。

1、在app.modules.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);
 });

二、post请求

发post请求和get请求的第一步一样,直接从第二步开始

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

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

3、post提交数据

consthttpOptions={ 
headers:newHttpHeaders({'Content-Type':'application/json'})
 };
varapi="http://127.0.0.1:3000/doLogin"; 
this.http.post(api,{username:'张三',age:'20'},httpOptions).subscribe(response=>{ console.log(response); 
});

三、Jsonp请求数据

1、在app.modules.ts中引入HttpClientModule、HttpClientJsonpModule并注入

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

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

import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient) { }

3、jsonp请求数据

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

四、Angular中使用第三方模块axios请求数据

1、安装axios

cnpminstallaxios--save

2、用到的地方引入axios

importaxiosfrom'axios';

3、具体使用

axios.get('/user?ID=12345')
 .then(function(response){ 
//handlesuccess console.log(response);
 }) 
.catch(function(error){
 //handleerror console.log(error); 
})
 .then(function(){
 //alwaysexecuted 
});
发布了176 篇原创文章 · 获赞 185 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Sophia_0331/article/details/89855299