user114338 user114338 - 2 months ago 7
TypeScript Question

Unable to assign variable within a subscriber

I have two bits of code, one which works and one which does not. Here's the first (working) version:

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


this correctly logs the JSON object my service sends to the console. But this:

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


does not work. when I try to log this.list to the console outside of the subscriber, it returns undefined. Anyone know what I'm doing wrong here?

Also, here's my service:

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

}


and the component in its entirety:

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

}

Answer

You are probably logging the result before the asynchronous call has returned. To test this, try adding the console.log immediately after the assignment in you subscription, like this:

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