这是我的服务TS文件:
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;
}
这是我的组件TS文件:
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);
}
}
在我的ngOnInit事件中,this.lists在控制台语句中以未定义的形式返回,如果我在“subscribe”部分将其悬停在它上面,则会显示“非法返回语句”。但是,Chrome说“http.get”本身正确返回,我可以看到那时的数据,所以我知道控制器方法没问题。
我简单地从组件TS文件本身开始使用它,但我认为最好将它分成一个服务文件,因为我需要来自几个地方的列表。
据我所知,我已经正确地遵循了所有教程,但很明显我错过了一些东西。有什么想法吗?