无法在订户中分配变量

时间:2016-09-04 16:36:07

标签: angular typescript rxjs

我有两位代码,一个有效,另一个无效。这是第一个(工作)版本:

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);}    
                    );  

不起作用。当我尝试将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);}    
                     );  
    }

}

1 个答案:

答案 0 :(得分:0)

您可能在异步调用返回之前记录结果。要对此进行测试,请尝试在订阅后立即添加console.log,如下所示:

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