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

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

问题描述

我是Angular2的新手.我想在我的MVC6项目中使用Angular2调用API.我已经尝试了很多方法(包括 Angular2调用ASP.NET Web API的指南)没有成功.

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.

推荐答案

我将看一下Github上的一些示例,看看其他人是如何做到的.为了使所有功能正常工作,有很多事情是正确的,并且在您启动并运行之前,错误可能很模糊.

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.

将Web API控制器类添加到您的项目中.为了确保起初一切正常,建议您将HttpGet属性硬编码为"api/values".

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..您需要angular2路由以不干扰ASP.NET的路由.这意味着如果出现404错误,则需要将index.html提供给客户端. app.Use lambda可以完成此任务.请注意,它在调用app.UseDefaultFiles()和app.UseStaticFiles()

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

设置完成后,您应该使用邮递员来测试API,以确保路由正确正在按您的意愿工作.如果这不起作用,则在Angular中将不起作用.我在Visual Studio中将 http://localhost:5001/设置为我的 App URL 项目调试设置.

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.

如果该方法正常运行,请继续使用Angular 2进行加载.您需要在html文件中的head标记之后使用base元素.这告诉Angular路由器URL的静态部分是什么:

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="/">

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

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

RxJS中的.do运算符非常方便.它将允许您调试是否正确地从API中获取值.有关更多详细信息,请参见 Andre Staltz的博客.

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.

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

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天全站免登陆