简体   繁体   中英

angular http.get not working

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM