【问题标题】:Angular 2 calling Web Api with json results not displayingAngular 2调用Web Api,json结果不显示
【发布时间】:2016-08-23 23:46:24
【问题描述】:

我与 Angular 1.5.x 的通话需要将 Devices 添加到 result.data

result.data.Devices

因此我的 Angular 1.x $http 调用是这样的:

var vm = this;
var dataService = $http;

dataService.get("http://localhost:42822/api/device")
        .then(function (result) {

vm.devices = result.data.Devices; 

我的 Angular 2 代码有点不同,我调用的是同一个 web api

如果我调用一个 .json 文件,那么它可以显示

private _productUrl = 'api/devices/devices.json';

但我不理解其中的一些代码,我看不到在哪里真正添加“设备”

private _productUrl = 'http://localhost:42822/api/device';

constructor(private _http: Http) { }

getProducts(): Observable<IDevice[]> {//Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IDevice[]>response.json())
        .do(data => console.log("All: " + JSON.stringify(data)))
        .catch(this.handleError);
}

这不是我要在“设备”或 html 模板中添加的地方吗?

【问题讨论】:

  • 这可能是因为IDevice 定义。尝试使用any 而不是IDevice
  • 这听起来不像是他的问题,因为他说他的 .json 文件正在工作If I call up a .json file then it works to display 所以我猜他的界面没问题。

标签: javascript angularjs json angular


【解决方案1】:

更新

getProducts 返回可订阅的 Observable 集合

.map((response: Response) =&gt; &lt;IDevice[]&gt;response.json())

这会在 http 请求完成后返回您的设备列表。

getProducts 被定义为控制器方法,您可以像这样订阅可观察的集合。

getProducts().subscribe(data =&gt; this.vm.devices = data)

或者更好地将它分成服务(例如DataService)

// constructor
constructor (private dataService: DataService) {}

displayData(): {
    this.dataService.getProducts()
        .subscribe(data => this.vm.devices = data);
}

【讨论】:

  • 我认为 OP 甚至没有“vm”,因为在他们的代码中他们用 Angular 1 谈论“vm.devices”,但他们从未在 Angular 2 部分显示任何这样的对象代码...我认为它不存在...
  • 我没有vm 不知道该怎么做 .subscribe(data => this.vm.devices = data); .....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
相关资源
最近更新 更多