简体   繁体   中英

Calling Asp.net MVC 5 controller using Angular 2 Http

I'm new to angular 2 and trying to call MVC controller from Angular on button click but whenever I click on button my page refreshes . Please help .Thanks In advance

My LoginComponent code

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { AuthenticationService } from '../services/authentication.service';
import { Router } from "@angular/router";

@Component({
    template: `
<md-card>
  <div class="container">
    <section id="content">
        <form [formGroup]='loginForm' action="" (ngSubmit)='onsubmit()'>
            <h1>Login</h1>
            <div>
             <md-input placeholder='Email' class="md-input" formControlName='email'></md-input>
                <div *ngIf="loginForm.controls.email.errors?.required && loginForm.controls.email.dirty"
                 class="alert alert-danger">
                             Email is required
                </div>
         </div>
            <div>
                 <md-input placeholder='Password' class="md-input" type='password' formControlName='password'></md-input>
            </div>
            <div>
                <input type="submit" value="Log in" />
                <a href="#">Lost your password?</a>
                <a href="#" [routerLink]="['/Signup']">Register</a>
            </div>
        </form><!-- form -->

    </section><!-- content -->
</div></md-card>`,
    styleUrls: ['../Content/AppStyles/login.css']
})

export class LoginComponent implements OnInit {
    public loginForm: FormGroup;
    private authenticationService: AuthenticationService;
    private router: Router;
    loading = false;
    returnUrl: string;
    ngOnInit() {
        this.loginForm = new FormGroup({
            email: new FormControl('', [<any>Validators.required]),
            password: new FormControl('', [<any>Validators.required]),
        });
    }
    onsubmit() {

        this.loading = true;
        this.authenticationService.login("xyz","abc").subscribe(data => {
           // this.router.navigate([this.returnUrl]);
        },
            error => {
                this.loading = false;
            }
        )
        console.log(this.loginForm.value);
    }
}

Authentication Service

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService {
    constructor(private http: Http) { }

    login(username: string, password: string) {
        console.log(username);
        return this.http.post('/Account/Login', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let user = response.json();
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }
            });
    }

    logout() {

        localStorage.removeItem('currentUser');
    }
}

My MVC Routing configuration is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace iShopping
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                 constraints: new
                 {
                     serverRoute = new ServerRouteConstraint(url =>
                     {
                         return url.PathAndQuery.StartsWith("/Account",
                             StringComparison.InvariantCultureIgnoreCase);
                     })
                 }

            );
        routes.MapRoute(
        name: "angular",
        url: "{*url}",
        defaults: new { controller = "Home", action = "Index" } // The view that bootstraps Angular 2
    );

        }
    }
}

It's hard to tell without seeing your Route configuration for both the angular app and the MVC app.

But a likely cause of error is that you have configured your MVC app to ignore all routes and let them fall back to your index.html to let angular handle your routing.

If this happens, and you have no angular route matching /account/login , it will likely fall back to your default route (if you have one?). If this happens, your page will not really refresh, but rather load the component of your default route.

Please revisit your route configurations to see if this is the issue. An easy way to see if this could be to case is to inspect if the /account/login us being hit at all.

If this is the problem, consider prefixing your MVC routes with for example /api/... , then make a route rule that api routes to go your controllers, everything else goes to angular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM