Angular2でJSONPを使ってサーバー通信する方法をまとめました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)
※目次をクリックすると目次の下部にコンテンツが表示されます。
JSONPとは?
・JSONP(JSON with padding)とは、scriptタグを使用してクロスドメインなデータを取得する仕組みのこと。
・HTMLのscriptタグ、JavaScript(関数)、JSONを組み合わせて実現される。
・ブラウザなどに実装されている”同一生成元ポリシー”という制約により、Webページは通常、自分を生成したドメイン以外のドメインのサーバと通信することはできない。
・HTMLのscriptタグのsrc属性には別ドメインのURLを指定して通信することができるという点を利用することによって別ドメインのサーバからデータを取得することが可能になる。
例)JSONPを使わずに別ドメインのサーバーにリクエストを送信した場合のエラー
XMLHttpRequest cannot load http://192.168.1.2/ng/heroes.json. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access.
・HTMLのscriptタグ、JavaScript(関数)、JSONを組み合わせて実現される。
・ブラウザなどに実装されている”同一生成元ポリシー”という制約により、Webページは通常、自分を生成したドメイン以外のドメインのサーバと通信することはできない。
・HTMLのscriptタグのsrc属性には別ドメインのURLを指定して通信することができるという点を利用することによって別ドメインのサーバからデータを取得することが可能になる。
例)JSONPを使わずに別ドメインのサーバーにリクエストを送信した場合のエラー
XMLHttpRequest cannot load http://192.168.1.2/ng/heroes.json. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access.
JSONPを使ったサンプル作成
①JSONP_PROVIDERS、Jsonpサービスをインポート
import {JSONP_PROVIDERS, Jsonp, URLSearchParams} from ‘@angular/http’;
constructor(private _jsonp: Jsonp) {}
:
bootstrap(AppComponent, [JSONP_PROVIDERS]);
②URLSearchParamsサービスをインポート(Searchパラメータを指定する場合)
以下のようなSearchパラメータを指定する場合、URLSearchParamsサービスをインポートします。
&key1=value1&key2=value2&key3=value3
URLSearchParamsサービスを使って、キー:値ペアのparamsオブジェクトを定義する。
import {JSONP_PROVIDERS, Jsonp, URLSearchParams} from ‘@angular/http’;
constructor(private _jsonp: Jsonp) {}
:
bootstrap(AppComponent, [JSONP_PROVIDERS]);
②URLSearchParamsサービスをインポート(Searchパラメータを指定する場合)
以下のようなSearchパラメータを指定する場合、URLSearchParamsサービスをインポートします。
&key1=value1&key2=value2&key3=value3
URLSearchParamsサービスを使って、キー:値ペアのparamsオブジェクトを定義する。
public params = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
・・・
var params = new URLSearchParams();
params.set('key1', this.params.key1);
params.set('key2', this.params.key2);
params.set('key3', this.params.key3);
③Jsonpサービスを使って送信
・URLに”callback=JSONP_CALLBACK”を付与して送信。
サーバーはこの関数名を取得し、処理をする。
let url = '/wp/jsonp.php?callback=JSONP_CALLBACK';
this._jsonp
.get(url, { search: params })
.subscribe(
res => {
this.results = res.json();
this.json_url = res.url;
},
error => alert(error));
※サーバー側のPHPコード
<?php
$output = array(
‘key1’ => ‘res_’ . $_GET[‘key1’],
‘key2’ => ‘res_’ . $_GET[‘key2’],
‘key3’ => ‘res_’ . $_GET[‘key3’]
);
echo $_GET[‘callback’] . “(” . json_encode($output). “)”;
?>
デモ
Angular : 4.4.3(2.0.0でも動作確認済み)
Bootstrap : 3.x
関連記事の目次
Bootstrap : 3.x
<html>
<head>
<title>Angular 2 Demo</title>
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
<script src="https://npmcdn.com/systemjs@0.19.39/dist/system.src.js"></script>
<script src="./js/systemjs.config.js"></script>
<script>
System.import('./ts/app.ts').catch(function(err){ console.error(err); }); </script>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="container">
<my-app>Loading...</my-app>
</div>
</body>
</html>
(systemjs.config.js)
(function (global) {
var ngVer = '@4.4.3';
System.config({
transpiler: 'ts',
typescriptOptions: {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"strict": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
'npm:': 'https://unpkg.com/'
},
map: {
'app': 'app',
'@angular/animations': 'npm:@angular/animations' + ngVer + '/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + ngVer + '/bundles/animations-browser.umd.js',
'@angular/core': 'npm:@angular/core' + ngVer + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + ngVer + '/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common' + ngVer + '/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + ngVer + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + ngVer + '/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + ngVer + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + ngVer + '/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router' + ngVer + '/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms' + ngVer + '/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs@5.0.1',
'tslib': 'npm:tslib/tslib.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.3.2/lib/typescript.js',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { JsonpModule, Jsonp, URLSearchParams } from '@angular/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'my-app',
template: `
<strong>JSOPデモ</strong><br />
<span>送信データ</span><br />
{{params|json}}<br />
<button (click)="send()">送信</button><br />
<span>送信URL</span><br />
{{json_url|json}}<br />
<span>応答データ</span><br />
{{results|json}}<br />
`
})
export class AppComponent {
constructor(private _jsonp: Jsonp) {}
public results;
public json_url;
public params = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
send () {
var params = new URLSearchParams();
params.set('key1', this.params.key1);
params.set('key2', this.params.key2);
params.set('key3', this.params.key3);
let url = '/wp/jsonp.php?callback=JSONP_CALLBACK';
this._jsonp
.get(url, { search: params })
.subscribe(
res => {
this.results = res.json();
this.json_url = res.url;
},
error => alert(error));
}
}
@NgModule({
imports: [
BrowserModule,
JsonpModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);