how can I get and post an action using angular 2 in MVC

后端 未结 1 1305
暗喜
暗喜 2020-12-20 05:50

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:

Let say I have an EmployeeController with 2 actions:

相关标签:
1条回答
  • 2020-12-20 06:43

    As promised :

    From the Controller side : (controller is named APIConnexionController.cs)

    [HttpGet]
    public IActionResult Connexion(string aLogin, string aMdp)
    {
       // Do your stuff
    }
    

    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 (in my case)

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

    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']);
                }
            });
    }
    
    0 讨论(0)
提交回复
热议问题