我是JavaScript和Mean堆栈框架的新手。我正在尝试构建一个网页,其中着陆页应该有一个标题和登录表单。如果用户身份验证良好,则应重定向到主页,否则会重定向到同一目标网页,但会出现Incorrect credentials
之类的错误。我正面临一个问题,我可以对用户进行身份验证,但是当我尝试更新主页的组件时,它会显示在登录表单下方,而不是替换登录表单。我需要用主页内容替换登录。
以下是我的app.component.ts
:
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { LoginService } from '../services/login.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
//styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(private loginService: LoginService,
private route: ActivatedRoute,
private router: Router) {
console.log("Form Component Start");
}
onSubmit(form: NgForm) {
var user = {
email: form.controls['email'].value,
password: form.controls['password'].value
};
this.loginService.authenticateAdmin(user).subscribe(
data => {
console.log("success status 200" + data.status);
this.router.navigateByUrl('/home');
},
err => {
console.log("error status" + err.status);
this.router.navigateByUrl('/');
}
);
}
}
这是我的login.service.ts
:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, RequestMethod } from "@angular/http";
import { Observable } from "rxjs/Rx";
import 'rxjs/add/operator/map';
@Injectable()
export class LoginService {
constructor(private http: Http) { }
// Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
// The entire operation will result in an error state if any single request fails.
authenticateAdmin(user) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
//let headers = new Headers({ 'Content-Type': 'application/json' }); //tobe done
let options = new RequestOptions({ method: RequestMethod.Post, headers: headers });
let body = this.serializeObj(user);
alert(body);
return this.http.post('http://localhost:8080/api/admin/authenticate', body, options).map((res: Response) => {
//res.json()
console.log("hjk");
let details = {detail:res.json(),status: res.status};
return details;//Observable..throw(details);
})
.catch((err: Response) => {
//let details = err.json();
//return Observable.throw(details);
console.log("jkll");
let details = {detail:err.json(),status: err.status};
return Observable.throw(details);
});
}
private serializeObj(obj) {
var result = [];
for (var property in obj)
result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));
return result.join("&");
}
}
以下是home.component.ts
:
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
//selector: 'app-root',
template: '<div>Welcome to home page</div>'
})
export class HomeComponent {
}
这是我的app.component.html
:
<div>
<nav class="navbar navbar-default navigation-clean-button" style="background-color:#294e80;height:70px;">
<div class="container">
<div class="navbar-header"><a class="navbar-brand navbar-link" href="#" style="color:rgb(255,255,255);">Aao Padhe - Admin UI</a>
<button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>
</div>
<div class="collapse navbar-collapse" id="navcol-1">
<ul class="nav navbar-nav">
<li class="dropdown"><a class="dropdown-toggle hidden-xs hidden-sm hidden-md hidden-lg" data-toggle="dropdown" aria-expanded="false" href="#" style="color:rgb(255,255,255);">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li role="presentation"><a href="#">First Item</a></li>
<li role="presentation"><a href="#">Second Item</a></li>
<li role="presentation"><a href="#">Third Item</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div class="login-clean">
<div>
<form #loginform = "ngForm" (ngSubmit) = "onSubmit(loginform)" style="height:441px;">
<div class="illustration"><i class="icon ion-ios-navigate" style="color:#294e80;"></i></div>
<div class="form-group">
<input class="form-control" type="email" name="email" #email="ngModel" placeholder="Email" ngModel required>
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" #password="ngModel" placeholder="Password" ngModel required>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit" style="background-color:#294e80;">Log In</button>
</div><a href="#" class="forgot" style="height:50px;">Forgot your email or password?</a></form>
</div>
</div>
<router-outlet></router-outlet>
这是index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700">
<link rel="stylesheet" href="assets/fonts/ionicons.min.css">
<link rel="stylesheet" href="assets/css/Header-Blue.css">
<link rel="stylesheet" href="assets/css/Login-Form-Clean.css">
<link rel="stylesheet" href="assets/css/Navigation-with-Button1.css">
<link rel="stylesheet" href="assets/css/Registration-Form-with-Photo.css">
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body style="margin-left:0px;">
<div></div>
<app-root></app-root>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
登录后看起来像:
答案 0 :(得分:0)
我会在组件上使用* ngIf来隐藏/显示,具体取决于检查用户是否经过身份验证的某些条件。
尝试这样的事情......
<div *NgIf="!isAuthenticated()">
<form #loginform = "ngForm" (ngSubmit) = "onSubmit(loginform)" style="height:441px;">
当然,你必须将isAuthenticated函数添加到你的ts代码中。
* NgIf文档在这里https://angular.io/api/common/NgIf