場景
Ionic介紹以及搭建環境、新建和運行項目:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106308166
在上面搭建起來項目的基礎上,實現請求後臺服務端數據並加載顯示。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公衆號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
項目根模塊app.module.ts中引入模塊
打開app.module.ts
import {HttpClient, HttpClientModule} from '@angular/common/http';
並添加聲明
imports: [BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule
})
],
在需要使用的組件中引入
比如這裏要在tab2這個組件中使用HttpClient請求數據,那麼在tab2.page.ts中引入
import { HttpClient } from '@angular/common/http';
並聲明
constructor(private http: HttpClient) {}
實現頁面初始化後加載數據
爲了實現當前tab2頁面加載完成後就請求數據,所以在tab2.page.ts中添加生命週期方法
ngOnInit() {
//清空請求結果的list
this.resultList = [];
//get請求數據
this.loadData();
}
當前頁面加載完成後就會執行ngOnInit裏面的代碼,首先會將存儲結果的list清空,然後執行請求數據的方法。
此塊的完整示例代碼
resultList: any; // 保存結果數據的數組
constructor(private http: HttpClient) {}
ngOnInit() {
//清空請求結果的list
this.resultList = [];
//get請求數據
this.loadData();
}
然後在加載數據的方法loaData中
public loadData() {
this.getResult().then((res: any) => {
console.log(res);
// 把結果數據壓入結果數組列表中。
res.forEach((element: never) => {
this.resultList.push(element);
});
}).catch(err => {
console.error(err);
});
}
將getResult方法的返回結果存儲到當前頁面的resultList中,那麼方法getResult方法就是具體請求數據的方法
public getResult() {
const url = "http://localhost:3000/news";
const method = 'GET';
const options = { params: { 'badao': '霸道的程序猿'} };
return this.http.request(method, url, options).toPromise();
}
url:請求數據的後臺服務端地址
method:標識是GET請求還是POST請求
options:設置請求參數等,這裏傳遞了一個badao參數
前端搭建完成。
運行項目
ionic serve
打開瀏覽器輸入:
http://localhost:8100
然後點擊下面導航欄的tab2
搭建Expres後臺服務端程序
前面前端請求後臺的url是http://localhost:3000/news
請求結果是返回一個數組。
新建一個文件夾nodeServe,然後在此文件夾下新建app.js和package.json兩個文件
package.json
{
"dependencies": {
"ejs": "^2.5.6",
"express": "^4.15.3",
"socket.io": "^2.0.3",
"body-parser": "~1.17.1"
}
}
app.js
var express = require('express');
var app= express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
/*express允許跨域*/
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
if(req.method=="OPTIONS") res.send(200);
else next();
});
//app.use(express.static(path.join(__dirname, 'public')));
app.get('/',function(req,res){
res.send('首頁');
})
app.post('/dologin',function(req,res){
console.log(req.body);
res.json({"msg":'post成功'});
})
app.get('/news',function(req,res){
//console.log(req.body);
//res.jsonp({"msg":'這是新聞數據'});
console.log("接收到的參數爲:"+req.query.badao);
res.send(["公衆號:霸道的程序猿","關注推送編程教程","歡迎關注"])
})
app.listen(3000,'127.0.0.1');
運行後臺服務端
在上面的nodeServe文件夾下打開命令行,確保電腦上已經安裝node
安裝依賴
npm install
或者
cnpm install
運行服務端程序
node app.js
然後打開瀏覽器輸入:
http://localhost:3000
如果出現以下頁面則是運行成功
然後輸入上面請求的地址查看返回的數據
重新運行前端ionic項目然後點擊tab2,查看服務端的控制檯,已經接受到傳遞的參數。
然後在前端loadData中打斷點查看獲取的數據
此時打開tab2.page.html將獲取的後端數據顯示
<ion-content [fullscreen]="true">
<ul>
<li *ngFor="let item of resultList">{{item}}</li>
</ul>
</ion-content>
效果
示例代碼下載
代碼見下面文章末尾
Ionic+Angular+Express實現前後端交互使用HttpClient發送get請求數據並加載顯示(附代碼下載)