Angular2 - 无法从API检索数据
问题描述:
我目前正在构建一个访问我构建的MVC Web API的Angular2应用程序。但是,它似乎没有检索任何数据。我明显错过了一些东西,但我不确定是什么。Angular2 - 无法从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所以任何帮助将不胜感激。
感谢,
答
右键我设法得到它通过使用可观察到的,而不是一个承诺工作。
我的服务方法现在看起来是这样的:
public GetAll =(): Observable<RepackIndex[]> => {
return this.http.get(this.baseUrl)
.map((response: Response) => <RepackIndex[]>response.json())
.catch(this.handleError);
}
我的组件调用现在看起来是这样的:
getRepacks(): void{
this.repackService.GetAll()
.subscribe((data:RepackIndex[]) => this.repacks = data,
error => console.log(error),
() => console.log('Get All repacks complete'));
}
我找到了答案here
希望这可以帮助别人否则
你好吗确定'https:// localhost:44321/api/Repack/All'返回正确的结果? –
是像我说我在尝试小提琴手确切的网址(复制和粘贴),它返回成功 – DaRoGa
对不起,错过了一部分:) –