Login

ionic5 code snippet: HTTP network request

Author:neo yang Time:2020/04/18 Read: 7740
Versions used: ionic5 and angular8 1. GET 1. Introduction at the beginning of app.module.js: import […]

使用版本:ionic5和angular8

一、GET

1、app.module.js

开头引入:

import { HttpClientModule } from '@angular/common/http';

imports中加入:

imports: [
...
HttpClientModule,
...
],

2、页面的ts文件(xxx.page.ts)中

开头引入:

import { HttpClient} from '@angular/common/http';

constructor中:

constructor( 
private http: HttpClient
) { }

ngOnInit()或其它函数中:

var url = "https://xxxxxx" ;    
this.http.get(url).subscribe(
data => {
console.log(data);
},
error => {
console.log('error');
})

2、POST

1、app.module.js

同GET。

2、页面的ts文件(xxx.page.ts)中

开头引入:(注意引入HttpHeaders,post请求要设置header)

import { HttpClient , HttpHeaders} from '@angular/common/http';

constructor中:

同GET。

ngOnInit()或其它函数中:

var url = "https://xxxxxx" ; 
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
this.http.post('url',{
key1: value1,
key2: value2
} ,httpOptions)
  • header中’Content-Type’: ‘application/json’是一个常见的header。根据你的需要配置。
  • key和value,为post的参数。

3、JSONP

1、app.module.js

开头引入:

import { HttpClientModule,HttpClientJsonpModule } from '@angular/common/http';

imports中加入:

imports: [
...
HttpClientModule,
HttpClientJsonpModule,
...
],

2、页面的ts文件(xxx.page.ts)中

开头引入:

同GET。

constructor中:

同GET。

ngOnInit()或其它函数中:

var url="https://xxxxxx";   this.http.jsonp(url,"callback").subscribe(
data=>{
console.log(data);
},error=>{
console.log('error');
})



copyright © www.lyustu.com all rights reserved.
Theme: TheMoon V3.0. Author:neo yang