Angular2 - 无法从API检索数据

时间:2016-09-21 10:13:02

标签: http asp.net-web-api angular

我目前正在构建一个Angular2应用程序,访问我已构建的MVC Web API。但是,它似乎没有检索任何数据。我显然缺少一些东西,但我不确定是什么。

我知道我正在使用的URL与标题一起工作,因为我能够通过fiddler正确检索数据。

我的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相当新,所以任何帮助都会非常感激。

谢谢,

1 个答案:

答案 0 :(得分:0)

对,我已经设法通过使用可观察而不是承诺来使其工作。

我的服务方法现在看起来像这样:

public GetAll = (): Observable<RepackIndex[]> => {
      return this.http.get(this.baseUrl)
                    .map((response: Response) => <RepackIndex[]>response.json())
                    .catch(this.handleError);
}

我的Component调用现在看起来像这样:

getRepacks(): void{
        this.repackService.GetAll()
                            .subscribe((data:RepackIndex[]) => this.repacks = data,
                            error => console.log(error),
                            () => console.log('Get All repacks complete'));
}

我找到了答案here

希望这有助于其他人

相关问题