我如何将数据从组件A发送到组件B Angular 2 [英] How do i send data from component A to component B Angular 2

查看:73
本文介绍了我如何将数据从组件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.

推荐答案

非常有趣的问题,基本上可以解决您的问题是可观察/订阅者,当登录组件中的值更改时,您需要
进行监听,然后将其发送回导航栏组件以显示。

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发生了一些更改,例如用户登录成功。
和fire 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
})

如有疑问,请告诉我。

这篇关于我如何将数据从组件A发送到组件B Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆