【问题标题】:angular http.get not working角http.get不工作
【发布时间】:2018-03-04 20:00:51
【问题描述】:

这是我的服务 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 在控制台语句中返回为未定义,如果我将鼠标悬停在“订阅”部分中,它会显示“非法返回语句”。但是,Chrome 说“http.get”本身返回正确,我可以看到那个时候的数据,所以我知道控制器方法没问题。

我简要地从组件 TS 文件本身进行了这项工作,但我认为最好将其分离到一个服务文件中,因为我需要来自多个地方的列表。

据我所知,我已经正确地遵循了所有教程,但显然我遗漏了一些东西。有什么想法吗?

【问题讨论】:

标签: angular typescript asp.net-core http-get


【解决方案1】:

Http 请求是异步的。订阅中需要写console.log。

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

您还需要在您的应用程序中使用HttpClientModuleHttpModule 已弃用。

【讨论】:

  • 错误发生在订阅中,因此无论如何“this.lists”仍然是未定义的。另外,除了可用的 Http 之外,我没有其他任何东西,我猜你指的是比我的项目使用的更新版本的 Angular。
  • 我认为问题在于我对“this.lists”何时实际可用的误解。我明白您将控制台日志调用放在“订阅”中的意思。
猜你喜欢
  • 1970-01-01
  • 2018-03-16
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2017-08-29
相关资源
最近更新 更多