【发布时间】:2016-09-21 20:27:38
【问题描述】:
我目前正在构建一个 Angular2 应用程序来访问我构建的 MVC Web API。但是,它似乎没有检索任何数据。我显然错过了一些东西,但我不确定是什么。
我知道我使用的 URL 与标题一起使用,因为我能够通过提琴手正确检索数据。
我的repack.service.ts如下:
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { RepackIndex } from './RepackIndex';
@Injectable()
export class RepackService{
private baseUrl = 'https://localhost:44321/api/Repack/All';
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) { }
getAllRepacks(): Promise<RepackIndex[]>{
var data = this.http.get(this.baseUrl)
.toPromise()
.then(response => response.json().data as RepackIndex[])
.catch(this.handleError);
return data;
}
private handleError(error: any): Promise<any>{
console.error("An error occured in repack.service", error);
return Promise.reject(error.message || error);
}
}
这是我的组件:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RepackIndex } from './repackIndex';
import { RepackService } from './repack.service';
@Component({
selector: 'index',
templateUrl: 'app/index.component.html',
providers: [RepackService]
})
export class IndexComponent implements OnInit{
repacks: RepackIndex[];
selectedRepack: RepackIndex;
constructor(private router: Router, private repackService: RepackService) { }
onSelect(repack: RepackIndex): void{
this.selectedRepack = repack;
}
getRepacks(): void{
this.repackService.getAllRepacks().then(repacks => this.repacks = repacks);
}
ngOnInit(): void{
this.getRepacks();
}
}
我尝试设置断点并添加 console.log 行,但没有数据返回到组件。
我对 Angular2 还很陌生,因此我们将不胜感激。
谢谢,
【问题讨论】:
-
你确定
https://localhost:44321/api/Repack/All返回正确的结果吗? -
是的,就像我说的我已经在 fiddler 中尝试了确切的 url(复制和粘贴)并且它成功返回
-
对不起,错过了那部分:)
-
无后顾之忧:)
-
没有错误?请检查http请求是否启动(dev-tools)..请检查是否有任何响应(dev-tools)并将console.log放入您的服务内的
.then()..
标签: http asp.net-web-api angular