[ionic] http 元件

在 ionic 裡使用 http 元件時:
https://ionicframework.com/docs/native/http/

遇到Error: Uncaught (in promise): Error: StaticInjectorError[HTTP]: 的 error,發生的原因是沒有加入到 providers 清單裡,加入的範例,檔案在 /src/app/app.module.ts :

Add Plugins to Your App’s Module

After installing a plugin’s package, add it to your app’s NgModule.

...

import { Camera } from '@ionic-native/camera';

...

@NgModule({
  ...

  providers: [
    ...
    Camera
    ...
  ]
  ...
})
export class AppModule { }

 


如果是透過 ‘@angular/http’ 範例如下:

 

‘@angular/http’ 的在 “/src/app/app.module.ts” 設定:

import { Http } from ‘@angular/http’;
import { HttpModule } from ‘@angular/http’;

..

..

imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],


GET Example

this.posts = null;

this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot').map(res => res.json()).subscribe(data => {
    this.posts = data.data.children;
});

console.log(this.posts);

https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

POST Example

let headers = new Headers();
headers.append('Content-Type', 'application/json');

let body = { 
  message:"do you hear me?"
};

this.http.post('http://spstest.000webhostap..., JSON.stringify(body), {headers: headers})
 .map(res => res.json())
 .subscribe(data => {
   console.log(data);
  });
}

如果是要取 html 而不是 json,範例:

var response = this.http.get(link);
response.subscribe(
res => {
console.log(res.text());
let alert = this.alerCtrl.create({
title: ‘Responsed!’,
message: res.text(),
buttons: [‘Ok’]
});
alert.present()
},
err => {
console.log(err);
},
() => console.log(‘call http API Complete’)
);


使用
import { Http } from ‘@angular/http’;
在某些需要穿透 tunnel 的情況下會有錯誤,請改用
import { HTTP } from ‘@ionic-native/http’;
附註:使用  ‘@angular/http’ 只能在 iOS/Android 上開發,沒辦法透過 ionic serve 在PC 上測試。

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *