如何在home.component.html中显示值userName?
家/ home.component.html:
<p>
You are logged in! {{ userName }}
</p>
class HomeComponent home / home.component.ts:
import {AuthService} from './../auth/auth.service';
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {User} from '../auth/user';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styles: []
})
export class HomeComponent implements OnInit {
constructor(private _data: AuthService) {
}
ngOnInit() {
}
}
登录/ login.component.html:
<form class="example-form" [formGroup]="form" (ngSubmit)="onSubmit()">
User * <input matInput formControlName="userName" required>
<br />
Password * <input matInput type="password" formControlName="password" required>
<br />
<button mat-raised-button color="primary" type="submit">Login</button>
</form>
<router-outlet></router-outlet>
登录/ login.component.ts:
import {AuthService} from './../auth/auth.service';
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: FormGroup;
private formSubmitAttempt: boolean;
constructor(
private fb: FormBuilder,
private authService: AuthService
) {}
ngOnInit() {
this.form = this.fb.group({
userName: ['', Validators.required],
password: ['', Validators.required]
});
}
onSubmit() {
if (this.form.valid) {
this.authService.login(this.form.value);
}
this.formSubmitAttempt = true;
}
}
APP-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth/auth.guard';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '',
component: HomeComponent,
canActivate: [AuthGuard]
},
{ path: 'login',
component: LoginComponent
},
{ path: '**',
redirectTo: ''
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
app.modules.ts:
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {ReactiveFormsModule} from '@angular/forms';
import {AppComponent} from './app.component';
import {HomeComponent} from './home/home.component';
import {LoginComponent} from './login/login.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppMaterialModule} from './app-material/app-material.module';
import {FormsModule} from '@angular/forms';
import {AuthService} from './auth/auth.service';
import {AuthGuard} from './auth/auth.guard';
import './rxjs-operators';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
BrowserAnimationsModule,
AppMaterialModule,
FormsModule
],
providers: [AuthService, AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule {}
AUTH / auth.guard.ts:
import { Injectable } from '@angular/core';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router
} from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.authService.isLoggedIn // {1}
.take(1) // {2}
.map((isLoggedIn: boolean) => { // {3}
if (!isLoggedIn) {
this.router.navigate(['/login']); // {4}
return false;
}
return true;
});
}
}
AUTH / auth.service.ts:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { User } from './user';
@Injectable()
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false); // {1}
get isLoggedIn() {
return this.loggedIn.asObservable(); // {2}
}
constructor(
private router: Router
) {}
login(user: User) {
if (user.userName !== '' && user.password !== '' ) { // {3}
this.loggedIn.next(true);
this.router.navigate(['/']);
}
}
getUserName(user: User) {
return user.userName;
}
logout() { // {4}
this.loggedIn.next(false);
this.router.navigate(['/login']);
}
}
AUTH / user.ts:
export interface User {
userName: string;
password: string;
}
我正在尝试获取getUserName方法,但它不起作用
答案 0 :(得分:3)
我认为如果他已登录,您应该存储用户名的值:
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false); // {1}
private loggedUser= new BehaviorSubject<User>(<User>{}); // {1}
get isLoggedIn() {
return this.loggedIn.asObservable(); // {2}
}
login(user: User) {
if (user.userName !== '' && user.password !== '' ) { // {3}
this.loggedIn.next(true);
this.loggedUser.next(user);
this.router.navigate(['/']);
}
}
getUserName() {
return loggedUser.getValue().userName;
}
然后在你的家庭组件中:
userName:string;
ngOnInit() {
this.userName = _data.getUserName();
}
答案 1 :(得分:0)
感谢帖子,但在npm控制台中显示错误:
src / app / auth / auth.service.ts(11,24)出错:错误TS2554:预期有1个参数,但得到0。
行:
private loggedUser = new BehaviorSubject<User>();
auth / auth.service.ts中的AuthService类:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { User } from './user';
@Injectable()
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false);
private loggedUser = new BehaviorSubject<User>();
get isLoggedIn() {
return this.loggedIn.asObservable();
}
constructor(
private router: Router
) {}
login(user: User) {
if (user.userName !== '' && user.password !== '' ) {
this.loggedIn.next(true);
this.loggedUser.next(user);
this.router.navigate(['/']);
}
}
getUserName() {
return this.loggedUser.getValue().userName;
}
logout() {
this.loggedIn.next(false);
this.router.navigate(['/login']);
}
}