我如何在MVC中使用angular 2获取和发布动作 [英] how can I get and post an action using angular 2 in MVC
问题描述
我是Angular 2的新手,并且想知道在调用get和post操作时如何在mvc项目中使用它:
I am new to Angular 2 and would like to know how to use it in a mvc project when calling get and post actions:
比方说,我有一个EmployeeController,具有2个操作: 1)GetEmployee:列出员工信息 2)UpdateEmployee:更新员工信息
Let say I have an EmployeeController with 2 actions: 1) GetEmployee: which list employee info 2) UpdateEmployee: which update the employee info
不使用Angular 2,我们可以轻松地使用视图来处理它.但是,如果我想使用Angular 2,该怎么做?您能否提供一些示例,以便我学习如何使用Angular 2调用操作以获取或发布数据?
Without using Angular 2, we can easily use views to deal with it. However, if I want to use Angular 2, how can I do this? Could you please provide some samples so I can learn how to use Angular 2 to call actions to get or post data?
谢谢
推荐答案
如所承诺的:
从控制器端开始:(控制器名为 APIConnexionController.cs )
From the Controller side : (controller is named APIConnexionController.cs)
[HttpGet]
public IActionResult Connexion(string aLogin, string aMdp)
{
// Do your stuff
}
然后您可以从Angular2服务或组件中设置方法,以对控制器进行http调用,如下所示:
You can then setup your method from an Angular2 service or component to do an http call to your controller as follow :
auth.service.ts (在我的情况下)
private controllerURL: string = "/APIConnexion/auth";
login(aLogin: string, aMdp: string) {
// Setup parameters to send to ASP controller
let params = new URLSearchParams();
params.set("aLogin", aLogin); // => Left side must match Controller method parameter
params.set("aMdp", aMdp);
// Setup the http request
let lHttpRequestBody = params.toString();
let lControllerAction: string = "/connexion/?";
let lControllerFullURL: string = this.controllerURL + lControllerAction;
// Call the ASP.NET controller : APIController
return this.http.get(lControllerFullURL + lHttpRequestBody)
.map((res: any) => {
let data = res.json();
// Manage cases
switch (data.status) {
case "success":
this.isLoggedIn = true;
this.lcLogin = aLogin;
break;
case "error":
this.isLoggedIn = false;
throw new Error("Failure : " + data.message);
}
}
).catch(this.handleError);
}
然后只显示从Angular2组件到模板HTML的数据,或者执行某些操作,就像我的login()
方法:
And then just display the data you have from your Angular2 component to your template HTML, or execute some actions just like my login()
method :
// Manage authentication
login(username, password) {
this.authService.login(username, password)
.subscribe(() => {
// Call the service Method
if (this.authService.isLoggedIn) {
// Redirect the user to master component
this.router.navigate(['/master/dashboard']);
}
});
}
这篇关于我如何在MVC中使用angular 2获取和发布动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!