2016-10-19 38 views
0

私はAngular2の初心者です。Observablesの助けが必要です。角度2の観測可能な鎖

私はweb-appを持っており、リモートリソースから何らかのデータを取得し、ユーザーに表示します。

問題は、httpを使用してデータを取得し、それをローカルに格納し、その後に他のコンポーネントによって使用する必要があるということです。

私が試した次のスキーム:

data.ts

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

@Injectable() 
export class Airports { 
    private airportsUrl: string; 
    private cities: any; 
    private countries: any; 
    private routes: any; 
    private rawData: Observable<any>; 
    private errorMessage: any; 

    constructor(private http: Http) { 
     this.airportsUrl = ''; 
    } 

public get Cities() { 
    this.serverData.publishLast().refCount().subscribe(
     data => this.cities = JSON.stringify(data) 
    ); 
    return this.cities; 
} 

public get Countries() { 
    this.serverData.publishLast().refCount().subscribe(
     data => this.countries = JSON.stringify(data) 
    ); 
    return this.countries; 
} 

public get Routes() { 
    this.serverData.publishLast().refCount().subscribe(
     data => this.routes = JSON.stringify(data) 
    ); 
    return this.routes; 
} 

private init() { 
    this.serverData 
     .subscribe(
      data => this.rawData = data, 
      error => this.errorMessage = <any> error 
     ); 
} 
private get serverData() { 
    return this.http 
     .get(this.airportsUrl) 
     .map(this.parseData) 
     .catch(this.handleError); 
} 
private parseData(res: Response) { 
    let body = res.json(); 
    return body; 
} 
private handleError (error: any) { 
    let errMsg = (error.message) ? error.message : 
    error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
} 
} 

controler.ts

import '../../../public/css/styles.css'; 
import { Component, OnInit } from '@angular/core'; 

import { Airports } from './../data/data'; 

@Component({ 
    providers: [Airports], 
    selector: 'destination-selector', 
    styleUrls: ['./../views/view.cityselector.css'], 
    templateUrl: './../views/view.cityselector.html', 
}) 
export class CitySelector implements OnInit { 
    private cities: any; 
    private countries: any; 
    private routes: any; 

    constructor(private airports: Airports) { } 

    public ngOnInit() { 
     this.cities = this.airports.Cities; 
     this.countries = this.airports.Countries; 
     this.routes = this.airports.Routes; 
    } 
} 

view.cityselector.html

<main> 
    <div>Cities: {{ cities }}</div> 
    <div>Countries: {{ countries }}</div> 
    <div>Routes: {{ routes }}</div> 
</main> 

しかし、この方式で、私は3回(1ではなく)HTTPを呼び出し、この値{{ cities }}が、私はいくつかのローカル変数にHTTP、stroeそこからデータを取得し、地元をどのように使用できるか、だから、未定義

ですそれ以降は常に新しいHTTPを呼び出す

+0

http://stackoverflow.com/questions/36271899/whatに加入することになるデータを使用した成分に-is-the-the-way-of-an-angular-2-http-network-call-in –

答えて

0

これは、Angular2のhttp.getが、subscribeを呼び出すまで実際にデータを取得しないobservableを返すためだと思います。その後、あなたはそれにサブスクライブを呼び出すたびに、あなたは新しいhttp要求をしています。 代わりにhttp.getを即座に購読し、サービス内の変数に一度設定する必要があります。次に、あなたのサービスの公開関数がその変数の値の観測値を返すようにします。

This article by Cory Rylan was very helpful私が働いていたデータサービスを開始しました。

私のサービスが残りのアプリケーションのデータを管理していたところで、このようなことをしました。その後、私はのDataServiceをインポートしdataService.getDataの戻り値()

@Injectable 
 
export class DataService { 
 
    constructor(private http: Http){ 
 
    this.loadData(); 
 
    } 
 
    private _url = 'http://yoururlhere.com:3000/api/path'; 
 
    public _appData$: BehaviorSubject<any[]> = new BehaviorSubject([]); 
 
    private appData:any[] = []; 
 

 
    loadData() { 
 
    console.log('Making HTTP request, loading data...'); 
 
    this.http.get(this._url).map(this.extractData).subscribe(
 
     data => { 
 
     this.appData = data; 
 
     this._appData$.next(data); 
 
     }, 
 
     error => { 
 
     console.log(error); 
 
     } 
 
    ); 
 
    } 
 

 
    addData(newData){ 
 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
 
    let options = new RequestOptions({ 
 
     headers: headers 
 
    }); 
 
    
 
    this.http.post(this._url, newData, options).map(this.extractData).subscribe(data => {this.appData.push(data); this._appData$.next(this.appData);}); 
 

 
    } 
 
    getData(){ 
 
    return Observable.from(this._appData$); 
 
    } 
 

 
    private extractData(res: Response) { 
 
    let body = res.json(); 
 
    return body || {}; 
 
    } 
 
}

+0

しかし、私はこれをどうすればできるのですか?あなたは私に例を挙げることができますか? –

関連する問題