我正在学习angular2 / 4并尝试使用用户名和密码创建登录页面。我有两个组件LoginComponent和DashboardComponent。当用户输入用户名和密码时,仪表板应显示欢迎用户名消息(例如“欢迎ABC”)。我能够创建登录页面,但不确定如何处理问题的第二部分,即仪表板应该向我显示登录的用户。我按照下面的stackoverflow“Display username of user who logs in (Angular 2)”但是没有从中获得很多。以下是我的代码。任何plunker例子都非常感谢。我也查看了http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial,但它将登录详细信息存储在本地存储中并从那里获取。有没有其他方法可以在登录时获取用户名。提前致谢。代码如下。
auth.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map'
import { User } from "app/demo/domain/user";
@Injectable()
export class AuthService {
loginObject :User
isLoggedIn: boolean = false;
redirectUrl: string;
constructor(private http: Http) { }
login(username : string, password : string) {
this.loginObject ={username: username, password: password};
return this.http.post('http://localhost:8080/ui/api/login/'+username, this.loginObject)
.map((response: Response) => {
let user = response.json();
if (user) {
logged in between page refreshes
this.isLoggedIn = true;
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logout(): void {
this.isLoggedIn = false;
}
}
login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from "app/demo/service/auth.service";
@Component({
selector: 'login',
templateUrl: 'login.component.html',
})
export class LoginComponent {
message: string;
user: any = {};
constructor(public authService: AuthService, public router: Router) {}
login() {
this.authService.login(this.user.username,
this.user.password).subscribe(data => {
console.log(this.user.username);
// this.setMessage();
if (this.authService.isLoggedIn) {
// Get the redirect URL from our auth service
// If no redirect has been set, use the default
this.authService.redirectUrl = '/dashboard';
let redirect = this.authService.redirectUrl ?
this.authService.redirectUrl : '';
// Redirect the user
this.router.navigate([redirect]);
}
},
error => {
this.message ="Error: Username or password is incorrect";
});
}
logout() {
this.authService.logout();
this.message = 'Logged ' + (this.authService.isLoggedIn ? 'in' : 'out');
this.router.navigate(['/login']);
}
}
login.component.html
<!DOCTYPE html>
<html>
<head>
<script>document.write('<base href="' + document.location + '" />');
</script>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0,
maximum-scale=1.0, user-scalable=0"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>PrimeNG - ATLANTIS</title>
<!-- Layout CSS -->
<link rel="stylesheet" type="text/css" href="assets/theme/theme-blue.css">
<link rel="stylesheet" type="text/css" href="assets/layout/css/layout-
blue.css">
<link rel="stylesheet" type="text/css" href="assets/pages/primeng.min.css">
<!-- Ripple -->
<script src="jquery.js"></script>
</head>
<!-- 3. Display the application -->
<body class="login-body">
<div class="login-panel ui-fluid">
<div class="ui-g">
<div class="ui-g-12 logo-container">
<h1>Login to Your Account</h1>
<h2>WELCOME TO SKYCREEK</h2>
</div>
<p style="color: #ff0000;">{{message}}</p>
<form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm"
novalidate>
<div class="ui-g-12" [ngClass]="{ 'has-error': f.submitted &&
!username.valid }">
<input type="text" autocomplete="off" class="ui-inputtext ui-
corner-all ui-state-default ui-widget" name="username"
[(ngModel)]="user.username" #username="ngModel" placeholder="Username"
required />
<div *ngIf="f.submitted && !username.valid" class="help-block"
style="color: #ff0000;">Username is required</div>
</div>
<div class="ui-g-12" [ngClass]="{ 'has-error': f.submitted &&
!password.valid }">
<input type="password" autocomplete="off" class="ui-inputtext
ui-corner-all ui-state-default ui-widget" name="password"
[(ngModel)]="user.password" #password="ngModel" placeholder="Password"
required />
<div *ngIf="f.submitted && !password.valid" class="help-block"
style="color: #ff0000;">Password is required</div>
</div>
<div class="ui-g-12 button-container">
<button class="ui-button green-btn ui-widget ui-state-default
ui-corner-all ui-button-text-icon-left">Login</button>
</div>
</form>
</div>
</div>
</body>
</html>