Angular中与后端的数据交互方式(get/post/jsonp)

1.Get请求数据

//Angular5.x 以后 get、post 和和服务器交互使用的是 HttpClientModule 模块。
1、在 app.module.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 = "后端接口";
this.http.get(api).subscribe(response => {
console.log(response);
});

2.Post 提交数据

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

1、在 app.module.ts 中引入 HttpClientModule 并注入
import {HttpClientModule} from '@angular/common/http';
imports: [
BrowserModule,
HttpClientModule
]

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

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

3、post 提交数据
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

var api = "后端接口";
this.http.post(api,{username:'张三',age:'20'},httpOptions).subscribe(response => {
console.log(response);
});

3.Angular Jsonp请求数据

1、在 app.module.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 = "后端接口";
this.http.jsonp(api,'callback').subscribe(response => {
console.log(response);
});

 

你可能感兴趣的:(Angular,前端)