user114338 user114338 - 1 month ago 6x
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.listingsService
res => {console.log(JSON.parse(res));}

this correctly logs the JSON object my service sends to the console. But this: = this.listingsService
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';


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';

selector: 'listings',
templateUrl: './listings.component.html',
pipes: [DepluralizePipe],
providers: [ListingsService]

export class ListingsComponent{
constructor(private activatedRoute: ActivatedRoute,
private listingsService: ListingsService){}

params => this.title = params['title']
) = this.listingsService
res => {this.list = JSON.parse(res);}



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.listingsService
                .subscribe(res => {
                    this.list = JSON.parse(res);