How do i send data from component A to component B Angular 2(我如何将数据从组件 A 发送到组件 B Angular 2)
问题描述
我想在我的 NavbarComponent 上显示用户名,数据来自 LoginComponent.
I want to display the username on my NavbarComponent, the data coming from 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,没有成功.
I am sorry if there's too much code but basically i want to take data.user.username from LoginComponent in the onLoginSubmit() function, send it to NavbarComponent, use it in a variable and display it on the html. I tried to import the NavbarComponent, didn't work.
推荐答案
非常有趣的问题,基本上解决你的问题是Observable/subscriber
,你需要当登录组件中的值发生变化时监听并发送回导航栏组件显示.
Pretty Interesting question , basically solution to your problem is Observable/subscriber
, you need to
listen when the value changes in the login component and send it back to navbar component to display.
你可以像这样使用全局 Observable
you can use global Observable like this
假设您像这样在全局文件中创建一个 Observable
let suppose you create one Observable in your global file like this
public loggedInObs: Rx.Subject<any> = new Rx.Subject<any>();
public loggedInVar: boolean = false;
为了使用它,你必须导入一些像这样的依赖项
for using this you have to import some dependency like this
import { Observable } from 'rxjs/Rx';
import * as Rx from 'rxjs/Rx';
import 'rxjs/add/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
在您的登录组件中,您告诉 Angular 发生了一些更改,例如用户登录成功.并触发 observable ,以便 angular 能够在您设置 subscriber
的整个应用程序中监听该用户已登录应用程序.代码如下
Than in your login component you tell angular that there are some changes occurred like user login successfully.
and fire observable , so that angular will able to listen in whole app where you set subscriber
to listen that user
have logged in into app. code for this as below
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'});
}
现在您可以在导航栏组件中使用订阅者在应用程序的任何位置收听此内容
now you can listen to this using subscriber everywhere in the app like this in your navbar component
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
})
如果有任何疑问,请告诉我.
if any doubt let me know.
这篇关于我如何将数据从组件 A 发送到组件 B Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何将数据从组件 A 发送到组件 B Angular 2
基础教程推荐
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01