引入 HttpModule 、JsonpModule
普通的 HTTP 调用并不需要用到 JsonpModule,不过稍后我们就会延演示对 JSONP 的支持,所以现在就加载它,免得再回来浪费时间。
引入模块
import { HttpClientJsonpModule, HttpClientModule } from '@angular/common/http';
在 import 中注入模块
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientJsonpModule,
HttpClientModule
],
在使用文件引用
import {HttpClient,JsonpClientBackend} from '@angular/common/http'
在构造函数中声明
constructor(private http:HttpClient,private jsonp:JsonpClientBackend) {
}
HTTP 请求GET数据
/***请求数据 */ requestData(){ var url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1" this.http.get(url).subscribe(function(data){ // 如果请求成功运行此代码 console.log(data) },function(err){ // 如果请求失败运行此代码 console.log(err) }) }
返回的数据格式为 json 字符串。
解析获取的数据
ts 文件
import { Component, OnInit } from '@angular/core';
import { HttpClient, JsonpClientBackend } from '@angular/common/http'
@Component({
selector: 'app-mdata',
templateUrl: './mdata.component.html',
styleUrls: ['./mdata.component.css']
})
export class MdataComponent implements OnInit {
public list: any;
constructor(private http: HttpClient, private jsonp: JsonpClientBackend) {
}
ngOnInit() {
}
/***请求数据 */
requestData() {
var _that = this;
var url = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1"
this.http.get(url).subscribe(function (data) {
// 如果请求成功运行此代码
// console.log(data)
// 将json字符串转换为json对象 这个网址在请求的时候是对象,不必转换
// console.log(JSON.parse(data))
_that.list = data['result'];
console.log(_that.list)
}, function (err) {
// 如果请求失败运行此代码
console.log(err)
})
}
}
html 文件
<h2>请求数据</h2>
<button (click)="requestData()">请求数据</button>
<ul>
<li *ngFor="let item of list" >
{{item.title}}
</li>
</ul>
HTTP 请求Post数据
和GET请求一样,引入模块等一系列操作...
引入 headers 模块
private headers = new HttpHeaders({'Content-Type': 'application/json'});
设置请求头
private headers = new HttpHeaders({'Content-Type': 'application/json'});
使用 POST 请求数据
请求的后台是自己用node.js写的,代码如下:
1 var express = require('express'); 2 3 var app=express(); 4 5 var bodyParser = require('body-parser'); 6 app.use(bodyParser.json()); 7 app.use(bodyParser.urlencoded({ extended: false })); 8 9 10 //app.use(express.static(path.join(__dirname, 'public'))); 11 12 app.get('/',function(req,res){ 13 14 res.send('首页'); 15 16 17 18 }) 19 20 app.post('/dologin',function(req,res){ 21 22 console.log(req.body); 23 24 res.json({"msg":'post成功'}); 25 26 27 28 }) 29 30 app.get('/news',function(req,res){ 31 32 //console.log(req.body); 33 34 res.jsonp({"msg":'这是新闻数据'}); 35 36 }) 37 38 39 40 41 app.listen(3000,'127.0.0.1');