2016-08-09 23 views
12

Angular2が初めてです。 MVC6プロジェクトでAngular2を使用してAPIを呼び出す必要があります。私は成功なしで多くのことを(Angular2 calling ASP.NET Web APIのガイドを含む)試みました。Angular 2を使用してWeb APIコントローラを呼び出します。

私はどこから始めなければならないのか、どのファイルが必要なのか分かりません。

+1

を参照してください。http://stackoverflow.com/a/34758630/5043867 –

+1

*成功していない*とはどういう意味ですか?何が悪かったのか? – TRiG

答えて

12

私はGithubのいくつかの例を見て、他の人がどのようにしているかを見ていきたいと思います。そのすべてがうまくいくためにはちょうど良いことがいくつかあります。エラーは、あなたがそれを起動して実行するまでは漠然としている可能性があります。

プロジェクトにWeb APIコントローラクラスを追加します。ちょうどすべてが最初に動作していることを確認するために、あなたのHttpGet属性を "api/values"にハードコードすることをお勧めします。

ValuesController.cs。

public class ValuesController : Controller 
    { 
     [HttpGet("api/values")] 
     public IActionResult Get() 
     { 
      return new JsonResult(new string[] { "value1", "value2" }); 
     } 

Startup.Cs。 ASP.NETのルートに干渉しないようにするには、angular2ルートが必要です。つまり、404エラーが発生した場合は、index.htmlをクライアントに提供する必要があります。 app.Use lambdaがこれを実現します。あなたは、このセットアップを持っていたら、あなたがそれを望むように、あなたはルーティングが動作していることを確認するPostmanであなたのAPIをテストする必要があります

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     ... 
     var angularRoutes = new[] { 
      "/home" 
     }; 

     app.Use(async (context, next) => 
     { 
      if (context.Request.Path.HasValue && null != angularRoutes.FirstOrDefault(
       (ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase))) 
      { 
       context.Request.Path = new PathString("/"); 
      } 
      await next(); 
     }); 

     app.UseDefaultFiles(); 
     app.UseStaticFiles(); 
     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
     }); 
    } 

)それはapp.UseDefaultFilesへの呼び出し(前にあることに注意してください)とapp.UseStaticFiles(に。これが機能しない場合は、Angularで動作しません。私はhttp://localhost:5001/を私のVisual Studioプロジェクトのデバッグ設定で私ののアプリケーションURLに設定しました。

postman

それはそれはあなたがちょうどあなたのhtmlファイルの先頭のタグの後に基本要素を使用する必要があります角度2でロードするようになって上に移動し、正常に動作している場合。あなたのAPIから値を取得するためにAngular2でサービスを作成する必要があります次

<base href="/"> 

Index.htmlと

:これは、URLの静的な部分が何であるかを角度ルータに指示します RxJSでdataService.ts

import { Http, Response, Headers } from '@angular/http'; 
import 'rxjs/add/operator/map' 
import { Observable } from 'rxjs/Observable'; 
import { Configuration } from '../app.constants'; 

@Injectable() 
export class DataService { 
    private actionUrl: string; 
    constructor(private _http: Http, private _configuration: Configuration) { 
    this.actionUrl = 'http://localhost:5001/api/values/'; 
} 

public GetAll =(): Observable<any> => { 
    return this._http.get(this.actionUrl) 
     .map((response: Response) => <any>response.json()) 
     .do(x => console.log(x)); 
} 

.doという演算子は非常に便利です。 APIから値を正しく取得していることをデバッグできます。 Andre Staltz's blog for more detailsを参照してください。

最後に、サービスを使用するためのコンポーネントを作成します。 app.component.ts

import { Observable } from 'rxjs/Observable'; 
import { Component, OnInit } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { DataService } from '../services/DataService'; 

@Component({ 
    selector: 'app', 
    template: `My Values: <ul><li *ngFor="let value of values"> 
     <span>{{value.id}} </span> 
     </li></ul>`, 
    providers: [DataService] 
}) 

export class AppComponent implements OnInit { 
    public values: any[]; 
    constructor(private _dataService: DataService) {} 
    ngOnInit() { 
    this._dataService 
     .GetAll() 
     .subscribe(data => this.values = data, 
     error => console.log(error), 
     () => console.log('Get all complete')); 
    } 
} 
+0

鮮やかな答え!しかし、私はapp.constantsのデータサービスにエラーが発生しています。このapp.constantファイルはどのように見えるのですか? – RyeGuy

+2

ありがとう!それはそれに定数が入った単なるファイルです。私はスニペットに含めてはいけません。あなたは問題なくその行を削除することができるはずです。 – drinck

+0

素晴らしいありがとうございました! – RyeGuy

7

をこれは私が自分のアプリケーション(Web APIをコアとフロントエンドとしてangular2)それをやった方法です -

  1. すべてのアクション(GET、POST、PUT、DELETE)を提供するエンティティフレームワークを使用してコントローラを作成します。あなたがウェブAPIとエンティティフレームワークに新しいしている場合には、このリンクを参照してください - ウェブAPIでhttps://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html

  2. 有効CORS

[これはローカルホストからのクロス通信を処理するために行われる:3000(angular2)localhostに:59024(WEBAPI)]

まず、project.jsonに依存関係を追加 - "Microsoft.AspNetCore.Cors": "1.0.0",

を次にthis-

0等startup.csでCORSを有効
app.UseCors(builder => { 
    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); 
}); 

はあなたがここにCORSに関する詳細な情報を見つけることができます - https://docs.asp.net/en/latest/security/cors.html

3.In Angular2フロントエンドを、あなたはこのことができますかどうかを確認しthis-

@Injectable() 
export class WebApiService { 

    private _webApiUrl = 'http://localhost:59024/api/EmployeeMastersAPI'; 

     constructor(private _http: Http) { 

     } 

    getEmployees(): Observable<{}> { 
     return this._http.get(this._webApiUrl) 
      .map((response: Response) => <any[]> response.json()) 
      .do(data => console.log('All: ' + JSON.stringify(data))) 
      .catch(this.handleError) 
      ; 
    } 

    getEmployee(id: number): Observable<IEmployee> { 
     return this.getEmployees() 
      .map((emp: IEmployee[]) => emp.find(p => p.EMPID === id)); 
    } 

    addEmployeesDetails(emp) { 
     var headers = new Headers(); 
     headers.append('Content-Type', 'application/json; charset=utf-8'); 
     console.log('add emp : ' + JSON.stringify(emp)); 
     this._http.post(this._webApiUrl, JSON.stringify(emp), { headers: headers }).subscribe(); 

    } 

    private handleError(error: Response) { 
     console.error(error); 
     return Observable.throw(error.json().error || 'Server error'); 
    } 

} 

のようなあなたのサービス・コンポーネントを作成することができます。

関連する問題