2016-05-08 7 views
1

ここに、私のサービスタイプスクリプトファイルがあります。角度2のRxJSサブスクリプション演算子を使用しています。

import {Injectable} from '@angular/core'; 
import {Http, HTTP_PROVIDERS, Request, RequestOptions, Response, Headers} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 
export class CarService { 
    constructor(private http: Http) { } 
    Url: string = 'url/of/api'; 
    getCar(){ 
     var headers = new Headers(); 
      headers.append('API-Key-For-Authentification', 'my_own_key_goes_here'); 
      headers.append('Accept', 'application/json'); 
     var options = new RequestOptions({ headers: headers }) 
     return this.http.get(this.Url, options) 
      .map((res: Response) => res.json()) 
    } 
} 

上記成分は、以下の成分に注入される。

import {Component} from '@angular/core'; 
import {CarService} from 'path/to/car.service'; 

@Component({ 
    selector: 'home', 
    providers: [ CarService ], 
    template: ` 
     <div> 
      <button (click)="getCar()">Get Car</button> 
      <h2>The car has {{ tiresCount }} tires.</h2> 
     </div> 
    ` 
}) 
export class Home { 
    tiresCount: number; 
    constructor(private carService: CarService) { } 
    getCar() { 
     this.carService.getCar() 
      .subscribe(function(data){ 
       this.tiresCount = data.tires.count; 
       console.log(this.tiresCount); // 4 
     }; 
     console.log(this.tiresCount); // undefined 
    } 
} 

私がしようとしているのは、ボタンをクリックしたときにホームコンポーネントのビューにタイヤの数を表示することです。問題は、私が.subscribeカッコ内にconsole.log(this.tiresCount)を入れたときに、4をログに記録しますが、その外にログundefinedを記録することです。つまり、ローカルプロパティーtiresCountは新しい値を取得しなかったため、ビューには何も表示されません。

私は何かが明らかでないと思う。あるいは、おそらくObservablesやRxJSの理解が、私がそれらの新しいものとしてここに必要です。

+2

この場合、オブザーバブルは、本質的に非同期の約束とほぼ同じように機能します。その結果、あなたの外部のconsole.logは実行時に定義されることが期待されますが、実行されることはありません。 getCarへの呼び出しを起動し、THENが外部のconsole.logにヒットします。非同期応答が返される前に。 –

+0

これは理にかなっていますが、ローカルのプロパティ 'tiresCount'が返された後に新しい値を受け取らない理由を理解しようとしています。 – jayscript

答えて

4

subscribeメソッドでfunction(){..}の代わりにlambda expression "別名、矢印機能"を使用してください。 function(){...}を使用する場合、は、Homeコンポーネントクラスの代わりに関数自体を参照します。

getCar() { 
    this.carService.getCar() 
      .subscribe(data => { 
       this.tiresCount = data.tires.count; 
       console.log(this.tiresCount); // 4 
    }); 
    console.log(this.tiresCount); // undefined 
} 
someWhereElse(){ 
    console.log(this.tiresCount); // 4 , only after getCar().subscribe() resolves 
} 
+0

これは機能しました。 「これ」が意味することは重要だった。また、私はラムダ式の構文がステートメントの周りに{}を必要としているかどうかわかりませんでした。最初に無かったので、うまくいきませんでした。代わりに 'function(){..}'を使用しましたが、これは良い考えではありませんでした。ありがとう! – jayscript

+0

あなたは大体@jayscriptですが、ラムダ式は本体が複数行でない限り '{...}'を必要としません。それ以外の場合は、 '.subscribe(data => this.tiresCount = data.tires.count)'ということができます。 – Abdulrahman

関連する問題