我想在NavbarComponent上显示用户名,来自LoginComponent的数据。
login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder,FormGroup,Validators,FormControl } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form : FormGroup;
message;
messageClass;
constructor(
private formBuilder: FormBuilder,
private authService:AuthService,
private router: Router,
private flashMessagesService:FlashMessagesService
) {
this.createForm();
}
createForm(){
this.form=this.formBuilder.group({
username:['', Validators.required],
password:['', Validators.required]
})
}
onLoginSubmit(){
const user={
username: this.form.get('username').value,
password: this.form.get('password').value
}
this.authService.login(user).subscribe(data=>{
if(!data.success){
this.messageClass="alert alert-danger";
this.message=data.message;
}
else{
this.messageClass="alert alert-success";
this.message=data.message;
this.authService.storeUserData(data.token,data.user);
setTimeout(()=>{
this.router.navigate(['/profile']);
},2000);
this.flashMessagesService.show('Welcome to bloggy, '+ this.form.get('username').value +' !',{cssClass: 'alert-info'});
}
});
}
}
navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
usernameNav;
constructor(
private authService:AuthService,
private router:Router,
private flashMessagesService:FlashMessagesService
) { }
onLogoutClick(){
this.authService.logout();
this.flashMessagesService.show('You are logged out',{cssClass: 'alert-info'});
this.router.navigate(['/']);
}
ngOnInit() {
}
}
我很抱歉,如果代码太多,但基本上我想从onLoginSubmit()函数中的LoginComponent中获取data.user.username,将其发送到NavbarComponent,在变量中使用它并将其显示在HTML。 我试图导入NavbarComponent,但没有工作。
答案 0 :(得分:1)
非常有趣的问题,基本上解决您的问题的方法是Observable/subscriber
,您需要
当值在登录组件中更改并将其发送回导航栏组件以进行显示时进行侦听。
您可以像这样使用全局Observable
假设您在全局文件中创建一个Observable,如此
public loggedInObs: Rx.Subject<any> = new Rx.Subject<any>();
public loggedInVar: boolean = false;
使用它你必须导入一些像这样的依赖
import { Observable } from 'rxjs/Rx';
import * as Rx from 'rxjs/Rx';
import 'rxjs/add/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
在您的登录组件中,您告诉角度,用户登录成功后发生了一些变化。
和fire observable,以便angular能够在整个应用程序中监听你设置subscriber
以监听该用户
已登录到应用程序。代码如下
this.authService.login(user).subscribe(data=>{
if(!data.success){
this.messageClass="alert alert-danger";
this.message=data.message;
}
else{
this.messageClass="alert alert-success";
this.message=data.message;
localStorage.setItem('user_info', JSON.stringify(data.user))
/*for Global level observable fire here*/
this.global_service.loggedInVar = true; //i assume global_service here as your Global service where we declared variables
this.global_service.loggedInObs.next(this.global_service.loggedInVar);
this.authService.storeUserData(data.token,data.user);
setTimeout(()=>{
this.router.navigate(['/profile']);
},2000);
this.flashMessagesService.show('Welcome to bloggy, '+ this.form.get('username').value +' !',{cssClass: 'alert-info'});
}
现在,您可以在应用程序中的所有位置使用订阅者收听此信息,例如导航栏组件
userdata = JSON.parse(localStorage.getItem('user_info')); // in case of normal loading page
this.userName = userdata.user_name
this.global_service.loggedInObs.subscribe(res => { // in case of when without refresh of page
console.log('changes here in login');
userdata = JSON.parse(localStorage.getItem('user_info'));
this.userName = userdata.user_name
})
如果有任何疑问让我知道。