Angular http.get 不工作

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

这是我的服务 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”本身已正确返回,此时我可以看到数据,所以我知道 Controller 方法没问题。

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

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

最佳答案

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

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

您还需要使用 HttpClientModule在你的应用程序中。 HttpModule已弃用。

关于 Angular http.get 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49099806/

相关文章:

authentication - 如何使用/验证 AspNet.Security.OpenIdConnect.Server (RC1) 颁发的 token ?

javascript - 如何解决MomentJS和Asp.net Core之间的时差

node.js - 从 Angular 调用用户到 Node (MEAN)仅发送电子邮件和 _id 到 Angular

javascript - 在 angular2 应用程序中加载 JavaScript 文件

typescript - TS 非抽象类解释为抽象类

javascript - 如何循环遍历一个数组并获取id对应的name并将结果赋给另一个数组

azure - 通过 Web API 而不是 Graph API 重置 Azure AD 密码

html - 如何为特定的 UL 分配 Active Class?

用于单选按钮的 Angular2 Reactive Forms formControl

javascript - RXJS 中的 startWith 运算符真的被弃用了吗?