请求数据
Angular5.x以后,get、post和服务器交互使用的是HttpClientModule模块。
Get请求
- 在根组件app.module.ts中加入HttpClientModule模块 ```typescript import { BrowserModule } from ‘@angular/platform-browser’; import { NgModule } from ‘@angular/core’;
// 加入HttpClientModule模块 import { HttpClientModule } from ‘@angular/common/http’
import { AppComponent } from ‘./app.component’; import { NewsComponent } from ‘./components/news/news.component’;
@NgModule({ declarations: [ AppComponent, NewsComponent ], imports: [ BrowserModule, HttpClientModule // 加入HttpClientMoudle模块 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2.
在news组件中注入HttpClient,并使用HttpClient的get方法请求数据
```typescript
import { Component, OnInit } from '@angular/core';
// 引入HttpClient
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
public list:[] = [];
// 注入HttpClient
constructor(public httpClient:HttpClient) { }
ngOnInit(): void { }
getData() {
console.log('getData');
let url = 'http://a.itying.com/api/productlist';
// 通过httpClient的get方法请求接口并获取响应
this.httpClient.get(url).subscribe((response:any) => {
console.log(response);
this.list = response.result;
});
}
}
Post请求
出现浏览器跨域问题解决办法:
创建谷歌浏览器快捷方式,目标 设置为:
“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” —disable-web-security —user-data-dir=E:\Chrome_devUserData
谷歌浏览器设置跨域时,需要指定一个新用户文件夹,即
--user-data-dir
参数
- 在根组件app.module.ts中加入HttpClientModule模块 ```typescript import { BrowserModule } from ‘@angular/platform-browser’; import { NgModule } from ‘@angular/core’;
// 加入HttpClientModule模块 import { HttpClientModule } from ‘@angular/common/http’
import { AppComponent } from ‘./app.component’; import { NewsComponent } from ‘./components/news/news.component’;
@NgModule({ declarations: [ AppComponent, NewsComponent ], imports: [ BrowserModule, HttpClientModule // 加入HttpClientMoudle模块 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2.
在news组件中加入HttpClient、HttpHeaders,并通过HttpClient的post方法发送数据
```typescript
import { Component, OnInit } from '@angular/core';
// 引入HttpClient,HttpHeaders
import { HttpClient,HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
constructor(public httpClient:HttpClient) { }
ngOnInit(): void {
}
doLogin() {
console.log('doLogin');
// 请求头
const httpOptions = {
headers : new HttpHeaders({'Content-Type':'application/json'})
};
let url = 'http://localhost:8080/HelloWorld/login';
let params = {
username: 'zhangsan',
password: '123456'
};
this.httpClient.post(url, params, httpOptions).subscribe(response => {
console.log(response);
});
}
}
用java编写服务端servlet
@WebServlet(name = "testLogin", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 打印传入的内容
InputStream is = req.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line + "\n");
}
// 编写响应内容
PrintWriter out = resp.getWriter();
out.print("{\"result\":\"success\"}"); // 响应报文为json格式
}
}
jsonp请求
可以用jsonp来解决get请求的跨域问题。
服务器必须支持jsonp请求。
可以使用 http://xxx.xxx.xxx/xxx?callback=aaa 观察响应是否被包装了aaa,来测试是否支持jsonp。
有些服务器回调函数参数名不叫callback,可能是http://xxx.xxx.xxx/xxx?cb=aaa
- 在根模块app.module.ts中加入HttpClientModule、HttpClientJsonpModule模块 ```typescript import { BrowserModule } from ‘@angular/platform-browser’; import { NgModule } from ‘@angular/core’;
// 加入HttpClientModule、HttpClientJsonpModule import { HttpClientModule, HttpClientJsonpModule } from ‘@angular/common/http’
import { AppComponent } from ‘./app.component’; import { NewsComponent } from ‘./components/news/news.component’;
@NgModule({ declarations: [ AppComponent, NewsComponent ], imports: [ BrowserModule, // 加入HttpClientModule、HttpClientJsonpModule模块 HttpClientModule, HttpClientJsonpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2.
在news组件中使用jsonp发起请求
```typescript
import { Component, OnInit } from '@angular/core';
// 加入HttpClient
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {
// 注入HttpClient
constructor(public httpClient:HttpClient) { }
ngOnInit(): void {
}
// 使用jsonp进行请求
getJsonpData() {
console.log('getJsonpData');
let url = 'http://a.itying.com/api/productlist';
// 会在请求地址上加入callback参数
// 即最后请求的地址为:http://a.itying.com/api/productlist?callback=ng_jsonp_callback_0
this.httpClient.jsonp(url, 'callback').subscribe((response) => {
console.log(response);
});
}
}
使用第三方模块axios请求数据
- 在本项目安装axios模块
# --save 表示把这个模块写入package.json
cnpm install axios --save
- 自己封装一个httpservice服务,编写服务类.
此处为了方便调用而使用Promise封装了axios,也可以不进行封装,在需要用到的地方直接使用axios.get进行调用
import { Injectable } from '@angular/core';
// axios为export default默认导出,此处import时不需要加大括号
import axios from 'axios';
@Injectable({
providedIn: 'root'
})
export class HttpserviceService {
constructor() { }
// 使用Promise对axios.get进行封装
axiosGet(url:string) {
return new Promise((resolve) => {
axios.get(url)
.then(response => {
resolve(response);
});
});
}
}
在根组件app.module.ts中加入httpservice组件
在news组件中进行服务调用 ```typescript import { Component, OnInit } from ‘@angular/core’;
// 加入自己封装的HttpserviceService服务 import { HttpserviceService } from ‘src/app/services/httpservice.service’;
@Component({ selector: ‘app-news’, templateUrl: ‘./news.component.html’, styleUrls: [‘./news.component.less’] }) export class NewsComponent implements OnInit {
public list:[] = [];
// 注入自己封装的HttpserviceService服务
constructor(public axiosHttpService:HttpserviceService) { }
ngOnInit(): void { }
// 使用Promise方式调用封装的axiosGet方法
// 如果未使用Promise进行封装,则直接使用axios.get进行调用
getAxiosGetData() { let url = ‘http://a.itying.com/api/productlist‘; this.axiosHttpService.axiosGet(url).then((data) => { console.log(data); }); } } ```
- 最终的响应结果位于response.data.result中