0

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

        }
    }
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Yaa I found Problem In my MVC Routing .....I have applies constaints on MVC routing
Can You please Check my Routing Configuration ? I have changed it but still the same problem
Hmm, your RouteConfig looks fine to me, given that your MVC Controllers are following standard conventions (you have an AcountController, with a Login action). Maybe you can try to include the url in your http.post() call. For example try replacing this.http.post('/Account/Login', ... with this.http.post('http://localhost:your_port/Account/Login', .... Have you put a breakpoint in your Account/Login action to see if it ever gets hit?
Can you please share a Project online ?
No I don't sorry. I recommend looking into asp.net Core though, which is (in my opinion) easier to setup to work with SPAs. Here is a good guide for that: devblog.dymel.pl/2016/10/25/… And here is an application I have with a similar setup: github.com/fredrik-lundin/Flashcards
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.