LoginSignup
6
7

More than 5 years have passed since last update.

Angular2 & TypeScriptを勉強して分からなかったところや自分用メモをまとめていきます。
バージョン:alpha39とかその辺り

Angular2のビルトインライブラリにはHttpが含まれないため自分でインジェクトする必要がある。

app.ts
import {HTTP_PROVIDERS} from 'angular2/http';
  ...
bootstrap(MyAppComponent, [... HTTP_PROVIDERS]);

公式マニュアルにはHTTP_BINDINGS HTTP_PROVIDERSの2通り記載がある。
Httpの説明ではHTTP_PROVIDERSを使っているのでこっちを使う事にする。

呼んでみる

SampleClass
class SampleClass {
    constructor(http:Http) {
        http.get('sample.json');
    }

jsonが返ってこない...。

console.log()してみるとこんなやつがいる。

e {_isScalar: false}

誰?

Observable

Angular2のHttpのレスポンスはObservableを返す。
ObservableはMicrosoftのライブラリ RxJS のオブジェクトで、Angular1系で採用していた$qに比べて柔軟で便利な機能が用意されている。

  • メソッドチェインがthenだらけにならない
  • チェイン内でキャンセルできる
  • リトライなど便利そうなメソッドを持っている

RxJSのメソッド

jsonが欲しい...

SampleClass
class SampleClass {
    public list:string[];

    constructor(http:Http) {
        http.get('sample.json')
            .map(res => res.json())
            .subscribe(res => this.list = res)
        ;
    }

.map(res => res.json())

map()を使ってパース。
json()のほかにtext() blob()などが使える。

.subscribe(res => this.list = res)

subscribeは3つの関数を引数に取る。(success, error, complete)
ここではリクエストが成功した場合(第一引数)の処理を渡し、listプロパティに値を保存している。

何が入っているか見たい...

map() subscribe()のようにヘルパー関数を渡す場合は、関数内にデバッグ処理を入れる事ができる。

SampleClass
.map(res => {
    console.log(res);
    res.json();
})

// e {_body: "[{"no":1,"name":"ferret"}...

終わり

Observableが何者なのかよく分からなくて、ただのGETにとんでもなく時間がかかった。このサイトで導入のメリットから使い方まで親切に解説されている。

Angular2 Observables, Http, and separating services and components

上記サイトに記載されているリンク。
公式マニュアルでサンプルが足りないと思った時は頼りになりそう。
angular playground

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7