请求数据

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

Get请求

  1. 在根组件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 { }

  1. 2.
  2. news组件中注入HttpClient,并使用HttpClientget方法请求数据
  3. ```typescript
  4. import { Component, OnInit } from '@angular/core';
  5. // 引入HttpClient
  6. import { HttpClient } from '@angular/common/http';
  7. @Component({
  8. selector: 'app-news',
  9. templateUrl: './news.component.html',
  10. styleUrls: ['./news.component.less']
  11. })
  12. export class NewsComponent implements OnInit {
  13. public list:[] = [];
  14. // 注入HttpClient
  15. constructor(public httpClient:HttpClient) { }
  16. ngOnInit(): void { }
  17. getData() {
  18. console.log('getData');
  19. let url = 'http://a.itying.com/api/productlist';
  20. // 通过httpClient的get方法请求接口并获取响应
  21. this.httpClient.get(url).subscribe((response:any) => {
  22. console.log(response);
  23. this.list = response.result;
  24. });
  25. }
  26. }

Post请求

出现浏览器跨域问题解决办法:

创建谷歌浏览器快捷方式,目标 设置为:

“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” —disable-web-security —user-data-dir=E:\Chrome_devUserData

谷歌浏览器设置跨域时,需要指定一个新用户文件夹,即 --user-data-dir 参数

  1. 在根组件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 { }

  1. 2.
  2. news组件中加入HttpClientHttpHeaders,并通过HttpClientpost方法发送数据
  3. ```typescript
  4. import { Component, OnInit } from '@angular/core';
  5. // 引入HttpClient,HttpHeaders
  6. import { HttpClient,HttpHeaders } from '@angular/common/http';
  7. @Component({
  8. selector: 'app-news',
  9. templateUrl: './news.component.html',
  10. styleUrls: ['./news.component.less']
  11. })
  12. export class NewsComponent implements OnInit {
  13. constructor(public httpClient:HttpClient) { }
  14. ngOnInit(): void {
  15. }
  16. doLogin() {
  17. console.log('doLogin');
  18. // 请求头
  19. const httpOptions = {
  20. headers : new HttpHeaders({'Content-Type':'application/json'})
  21. };
  22. let url = 'http://localhost:8080/HelloWorld/login';
  23. let params = {
  24. username: 'zhangsan',
  25. password: '123456'
  26. };
  27. this.httpClient.post(url, params, httpOptions).subscribe(response => {
  28. console.log(response);
  29. });
  30. }
  31. }
  1. 用java编写服务端servlet

    1. @WebServlet(name = "testLogin", urlPatterns = "/login")
    2. public class LoginServlet extends HttpServlet {
    3. @Override
    4. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    5. // 打印传入的内容
    6. InputStream is = req.getInputStream();
    7. InputStreamReader isr = new InputStreamReader(is);
    8. BufferedReader br = new BufferedReader(isr);
    9. String line;
    10. while((line = br.readLine()) != null) {
    11. System.out.println(line + "\n");
    12. }
    13. // 编写响应内容
    14. PrintWriter out = resp.getWriter();
    15. out.print("{\"result\":\"success\"}"); // 响应报文为json格式
    16. }
    17. }

jsonp请求

可以用jsonp来解决get请求的跨域问题。

服务器必须支持jsonp请求。

可以使用 http://xxx.xxx.xxx/xxx?callback=aaa 观察响应是否被包装了aaa,来测试是否支持jsonp。

有些服务器回调函数参数名不叫callback,可能是http://xxx.xxx.xxx/xxx?cb=aaa

  1. 在根模块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 { }

  1. 2.
  2. news组件中使用jsonp发起请求
  3. ```typescript
  4. import { Component, OnInit } from '@angular/core';
  5. // 加入HttpClient
  6. import { HttpClient } from '@angular/common/http';
  7. @Component({
  8. selector: 'app-news',
  9. templateUrl: './news.component.html',
  10. styleUrls: ['./news.component.less']
  11. })
  12. export class NewsComponent implements OnInit {
  13. // 注入HttpClient
  14. constructor(public httpClient:HttpClient) { }
  15. ngOnInit(): void {
  16. }
  17. // 使用jsonp进行请求
  18. getJsonpData() {
  19. console.log('getJsonpData');
  20. let url = 'http://a.itying.com/api/productlist';
  21. // 会在请求地址上加入callback参数
  22. // 即最后请求的地址为:http://a.itying.com/api/productlist?callback=ng_jsonp_callback_0
  23. this.httpClient.jsonp(url, 'callback').subscribe((response) => {
  24. console.log(response);
  25. });
  26. }
  27. }

使用第三方模块axios请求数据

  1. 在本项目安装axios模块
    1. # --save 表示把这个模块写入package.json
    2. cnpm install axios --save
  1. 自己封装一个httpservice服务,编写服务类.

    此处为了方便调用而使用Promise封装了axios,也可以不进行封装,在需要用到的地方直接使用axios.get进行调用

  1. import { Injectable } from '@angular/core';
  2. // axios为export default默认导出,此处import时不需要加大括号
  3. import axios from 'axios';
  4. @Injectable({
  5. providedIn: 'root'
  6. })
  7. export class HttpserviceService {
  8. constructor() { }
  9. // 使用Promise对axios.get进行封装
  10. axiosGet(url:string) {
  11. return new Promise((resolve) => {
  12. axios.get(url)
  13. .then(response => {
  14. resolve(response);
  15. });
  16. });
  17. }
  18. }
  1. 在根组件app.module.ts中加入httpservice组件

  2. 在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:[] = [];

  1. // 注入自己封装的HttpserviceService服务

constructor(public axiosHttpService:HttpserviceService) { }

ngOnInit(): void { }

  1. // 使用Promise方式调用封装的axiosGet方法
  2. // 如果未使用Promise进行封装,则直接使用axios.get进行调用

getAxiosGetData() { let url = ‘http://a.itying.com/api/productlist‘; this.axiosHttpService.axiosGet(url).then((data) => { console.log(data); }); } } ```

  1. 最终的响应结果位于response.data.result中