3

This is my service TS file:

import { Http } from "@angular/http";
import { Inject, Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class ListService {

constructor(private http: Http, @Inject('BASE_URL') private baseURL: string) {}

public getAllLists(): Observable<ListModel[]> {
    return this.http.get(this.baseURL + 'api/List/LoadLists').map(resp => resp.json());
}

}

export interface ListModel {
ListID: number;
ListType: string;
ListValue: string;
ListOrder: number;
}

And this is my component TS file:

import { Component, OnInit } from '@angular/core';
import { ListModel, ListService } from '../shared/list/list.service';

@Component({
selector: 'job-post',
templateUrl: './job-post.component.html',
styleUrls: ['./job-post.component.scss'],
providers: [ListService]
})

export class JobPostComponent implements OnInit {

private lists: ListModel[];
private listService: ListService;

constructor(listService: ListService) {
    this.listService = listService;
}

ngOnInit() {
    this.listService.getAllLists()
        .subscribe(lists => this.lists = lists);
    console.log(this.lists);
}

}

In my ngOnInit event, this.lists comes back as undefined in the console statement, and if I hover on it in the "subscribe" part, it says "illegal return statement". However, Chrome says that the "http.get" itself returned properly and I can see the data at that point, so I know the controller method is okay.

I briefly had this working from the component TS file itself, but I figured it was better to separate it out into a service file since I'll need the lists from several places.

As far as I can tell, I've followed all the tutorials properly, but clearly I'm missing something. Any ideas?

1

1 Answer 1

5

Http request is async. You need to write console.log in subscribe.

ngOnInit() {
 this.listService.getAllLists()
  .subscribe(lists => {
    this.lists = lists;
    console.log(this.lists);
  }
}

Also you need to use HttpClientModule in you app. HttpModule is deprecated.

Sign up to request clarification or add additional context in comments.

2 Comments

The error occurs within the subscribe, so "this.lists" would still be undefined regardless of that. Also, I don't have anything another than Http available, I'm guessing you're referring to a more recent version of Angular than what my project is using.
I think the issue is my misunderstanding of when "this.lists" is actually available. I see what you mean about putting the console log call inside the "subscribe".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.