使用Angular 2 Http调用Asp.net MVC 5控制器

时间:2017-02-02 16:01:14

标签: asp.net-mvc angular

我是angular 2的新手,并试图在按钮点击时从Angular调用MVC控制器,但每当我点击按钮时我的页面都会刷新。请帮助。谢谢提前

我的LoginComponent代码

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

身份验证服务

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

我的MVC路由配置是:

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 个答案:

答案 0 :(得分:1)

如果没有看到角度应用和MVC应用的路由配置,很难说清楚。

但可能的错误原因是您已将MVC应用配置为忽略所有路由并让它们回退到index.html以让角度处理您的路由。

如果发生这种情况,并且您没有匹配/account/login的角度路线,它可能会回退到您的默认路线(如果您有一个?)。如果发生这种情况,您的页面将不会真正刷新,而是加载默认路由的组件。

请重新访问您的路线配置,看看是否存在问题。一个简单的方法,看看是否可能是这种情况是检查/account/login我们是否被击中。

如果这是问题所在,请考虑使用例如/api/...为您的MVC路由添加前缀,然后制定路由规则,使api路由到您的控制器,其他一切都转到角度。