2016-09-21 22 views
0

現在、私が構築したMVC Web APIにアクセスするAngular2アプリケーションをビルドしています。ただし、データを取得していないようです。私は明らかに何かが欠けていますが、私は何がわかりません。Angular2 - APIからデータを取得できません

私が使用しているURLは、ヘッダーと一緒に働くことがわかっています。私はフィドラーを通してデータを正しく取り出すことができます。

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); 
    } 
} 

そして、これは私のコンポーネントです::次のように

私repack.service.tsがある

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をかなり新しくしているので、どんな助けでも大歓迎です。

おかげで、

+0

'https:// localhost:44321/api/Repack/All'は正しい結果を返しますか? –

+0

はい、私はフィドラーで正確なURL(コピー&ペースト)を試してみたところ、それは正常に返されます – DaRoGa

+0

申し訳ありませんが、その部分を逃しました:) –

答えて

0

右私はそれが観測可能ではなく、約束を使って仕事を得るために管理しています。

マイサービスメソッドは次のようになります。

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

ホープこれは誰かに助けましたelse