2016-09-04 7 views
0

2ビットのコードがあります.1つは動作し、もう1つは動作しません。ここで最初の(作業)バージョンがあります:サブスクライバ内で変数を割り当てることができません

this.jobs = this.listingsService 
        .getListings(this.title) 
        .subscribe(
         res => {console.log(JSON.parse(res));}  
        ); 

これは正しくJSONは私のサービスは、コンソールに送信するオブジェクトを記録します。しかし、これは:

は動作しません。 this.listをサブスクライバの外部のコンソールに記録しようとすると、undefinedが返されます。誰でも私がここで間違っていることを知っていますか?

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

@Injectable() 

export class ListingsService{ 
constructor(private http: Http){} 
private url = 'http://localhost:3000/' 

getListings(query: string){ 
    return this.http.get(this.url + query).map(res => res.json()); 
    } 

} 

その全体がコンポーネント:非同期呼び出しが戻ってきた前に、おそらく結果をログに記録されている

import { Component, OnInit, OnChanges } from '@angular/core'; 
import { ActivatedRoute } from '@angular/router'; 
import { DepluralizePipe } from './depluralize.pipe'; 
import { ListingsService } from './listings.service' 
import 'rxjs/Rx'; 

@Component({ 
selector: 'listings', 
templateUrl: './listings.component.html', 
pipes: [DepluralizePipe], 
providers: [ListingsService] 
}) 

export class ListingsComponent{ 
title:string; 
list; 
jobs; 
constructor(private activatedRoute: ActivatedRoute, 
      private listingsService: ListingsService){} 

ngOnInit(){ 
    this.activatedRoute.params.subscribe( 
      params => this.title = params['title'] 
    ) 

    this.jobs = this.listingsService 
        .getListings(this.title) 
        .subscribe(
         res => {this.list = JSON.parse(res);}  
        ); 
    } 

} 
+0

:これをテストするには、次のように、すぐにあなたのサブスクリプションでの割り当て後console.logを追加してみてください? –

+0

私はモバイルですので、まだ編集できませんが、ngOnInit内にあるはずですが、this.jobsサブスクリプションの外にある – user114338

+1

'this.list'メンバーは、 'getListings'が完了しました。する前にログインしようとすると、' undefined'が返されます。それはおそらくケースです。 –

答えて

0

また、ここに私のサービスです。あなたのコードで、あなたが ``「コンソールにthis.listをログ」しようとするん

this.jobs = this.listingsService 
       .getListings(this.title) 
       .subscribe(res => { 
        this.list = JSON.parse(res); 
        console.log(this.list); 
       }); 
} 
関連する問題