使用 Angular 2 调用 Web API 控制器 [英] Call web API controller using Angular 2

查看:11
本文介绍了使用 Angular 2 调用 Web API 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular2 的新手.我想在我的 MVC6 项目中使用 Angular2 调用 API.我已经尝试了很多东西(包括

如果工作正常,继续使用 Angular 2 加载它.您需要在 html 文件中的 head 标记之后使用基本元素.这告诉 Angular 路由器 URL 的静态部分是什么:

Index.html

 <base href="/">

接下来,您需要在 Angular2 中创建一个服务以从您的 API 中获取值:dataService.ts

import { Http, Response, Headers } from '@angular/http';导入 'rxjs/add/operator/map'从 'rxjs/Observable' 导入 { Observable };从'../app.constants'导入{配置};@Injectable()导出类数据服务 {私人actionUrl:字符串;构造函数(私有_http:Http,私有_配置:配置){this.actionUrl = 'http://localhost:5001/api/values/';}public GetAll = (): Observable<any>=>{返回 this._http.get(this.actionUrl).map((response: Response) => <any>response.json()).do(x => console.log(x));}

RxJS 中的 .do 操作符非常方便.它将允许您调试您是否正确地从您的 API 获取值.请参阅 Andre Staltz 的博客了解更多详情.

最后,创建一个组件来使用该服务:app.component.ts

import { Observable } from 'rxjs/Observable';从'@angular/core'导入{组件,OnInit};从@angular/http"导入 { Http };从'../services/DataService'导入{DataService};@零件({选择器:'应用程序',模板:`我的价值观:<ul><li *ngFor="let value of values"><span>{{value.id}} </span></li></ul>`,提供者:[数据服务]})导出类 AppComponent 实现 OnInit {公共价值观:任何[];构造函数(私有_dataService:DataService){}ngOnInit() {this._dataService.得到所有().subscribe(data => this.values = data,错误=>控制台日志(错误),() =>console.log('全部完成'));}}

I am new to Angular2. I want to call an API using Angular2 in my MVC6 project. I have tried many things (including the guide at Angular2 calling ASP.NET Web API) without success.

I don’t know where I should start, or which files are needed.

解决方案

I'd look at some of the examples on Github to see how other people have done it. There are a number of things that have to be just right for it all to work, and the errors can be nebulous until you get it up and running.

Add a Web API Controller Class to your project. Just to make sure everything is working at first, I'd suggest hard coding your HttpGet attribute to "api/values".

ValuesController.cs. :

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

Startup.Cs. You need the angular2 routes to not interfere with ASP.NET's routes. This means you need to serve the index.html to the client if there is a 404 error. The app.Use lambda accomplishes this. Notice that it is before the calls to app.UseDefaultFiles() and app.UseStaticFiles()

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

Once you have this setup, you should test your API with Postman to make sure the routing is working as you want it to. If this doesn't work, it won't work in Angular. I have http://localhost:5001/ set as my App URL in my Visual Studio project Debug settings.

If that is working correctly, move on to getting it to load with Angular 2. You'll need to use the base element just after the head tag in your html file. This tells the Angular router what the static part of the URL is:

Index.html

    <base href="/">

Next you'll need to create a Service in Angular2 to Get the values from your API: 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));
}

The .do operator in RxJS is very handy. It will allow you to debug that you are correctly getting the values from your API. See Andre Staltz's blog for more details.

Finally, create a component to use the service: 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'));
  }
}

这篇关于使用 Angular 2 调用 Web API 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆