由于我从Angular 2.X迁移到Angular 5.X,我在执行HTTP请求时遇到了一些麻烦。我将从顶部开始。
这里我有一些测试MVC控制器和测试操作:
public class AccountController : ApiController
{
[HttpPost]
public ObjResultFunc Test()
{
return new ObjResultFunc(() => new { Data = "Some Text" });
}
}
和配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
然后,这是Http模块的当前AngularJS 2.X实现:
import { Injectable, Inject } from '@angular/core';
import { activeUrlToken } from '../app/providers'
import { Http, Response } from '@angular/http'
import { Observable } from 'rxjs/Rx';
@Injectable()
export class MVCAngularDataService {
constructor(private http: Http, @Inject(activeUrlToken) private API_URL: string) {
}
private handleError(error: Response | any) {
console.error('ApiService::handleError', error);
return Observable.throw(error);
}
public post(controller: string, action: string, data: any): Observable<any> {
return this.http
.post(this.API_URL + '/' + controller + '/' + action, data)
.map(response => {
return response;
})
.catch(this.handleError);
}
}
另请注意,this.API_URL
指向:
import { InjectionToken } from '@angular/core'
export const activeUrlToken = new InjectionToken('activeUrlToken');
export const activeUrl = 'http://localhost:3144/api';
调用测试函数有效:
this.mvcAngularService.post('Account', 'Test', null).subscribe(data => { console.log(data); });
然后我调整了MVCAngularDataService
以使用Angular 5.X中的HttpClient
模块,因为Http不再需要工作,建议现在使用5.X中的HttpClient,它看起来像遵循:
import { Injectable, Inject } from '@angular/core';
import { activeUrlToken } from '../app/providers'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs/Rx';
@Injectable()
export class MVCAngularDataService {
constructor(private http: HttpClient, @Inject(activeUrlToken) private API_URL: string) {
}
private handleError(error: Response | any) {
console.error('ApiService::handleError', error);
return Observable.throw(error);
}
public post(controller: string, action: string, data: any): Observable<any> {
return this.http
.post(this.API_URL + '/' + controller + '/' + action, data)
.catch(this.handleError);
}
}
现在每当我尝试执行一个简单的帖子时,我都会遇到404 - Not Found
错误:
我错过了什么?我强烈怀疑问题出在MVC服务器方面,但不知道从哪里开始寻找。
答案 0 :(得分:0)
转到nodu_modules
文件夹,然后检查@angular/common/http
我的@ angular / common / http是否遗失。