Я новичок в угловом 2 и пытаюсь вызвать контроллер MVC с помощью кнопки «Угловая кнопка», но всякий раз, когда я нажимаю кнопку, моя страница обновляется. Пожалуйста, помогите .THANKS ЗаранееВызов контроллера Asp.net MVC 5 с использованием Angular 2 Http
Мой 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);
}
}
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');
}
}
Моя конфигурация 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
);
}
}
}
Yaa Я нашел проблему В моей маршрутизации MVC ..... Я применил константы при маршрутизации MVC –
Можете ли вы проверить мою конфигурацию маршрутизации? Я изменил его, но все тот же вопрос –
Хмм, ваш RouteConfig выглядит хорошо для меня, учитывая, что ваши контроллеры MVC следуют стандартным соглашениям (у вас есть AcountController с действием входа). Возможно, вы можете попробовать включить URL-адрес в свой вызов 'http.post()'. Например, попробуйте заменить 'this.http.post ('/ Account/Login', ...' на 'this.http.post ('http: // localhost: your_port/Account/Login', ...'. Вы обнаружили ошибку в своем аккаунте/Войти, чтобы увидеть, будет ли он удаляться? –