0
我有兩位代碼,一位工作,一位不工作。這是第一個(工作)版本:無法在用戶中分配變量
this.jobs = this.listingsService
.getListings(this.title)
.subscribe(
res => {console.log(JSON.parse(res));}
);
這正確記錄我的服務發送到控制檯的JSON對象。但是:
this.jobs = this.listingsService
.getListings(this.title)
.subscribe(
res => {this.list = JSON.parse(res);}
);
不起作用。當我嘗試將此列表記錄到訂閱服務器之外的控制檯時,它將返回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);}
);
}
}
凡在你的代碼,你嘗試'「登錄this.list到控制檯」'? –
我在移動設備上,所以我不能編輯它,但它應該在ngOnInit中,但在this.jobs訂閱之外 – user114338
'this.list'成員將不具有值,直到異步操作'getListings'已經完成,所以如果你嘗試在它完成之前記錄它,你會得到'undefined'。可能是這種情況。 –