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);}
);
}
}
:これをテストするには、次のように、すぐにあなたのサブスクリプションでの割り当て後
console.log
を追加してみてください? –私はモバイルですので、まだ編集できませんが、ngOnInit内にあるはずですが、this.jobsサブスクリプションの外にある – user114338
'this.list'メンバーは、 'getListings'が完了しました。する前にログインしようとすると、' undefined'が返されます。それはおそらくケースです。 –