javascript - 我如何将数据从组件A发送到组件B Angular 2

标签 javascript angular components frontend

我想在我的 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,但没有成功。

最佳答案

非常有趣的问题,基本上解决你的问题是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';

在您的登录组件中,您告诉 Angular 发生了一些更改,例如用户登录成功。 并触发 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
})

如果有任何疑问,请告诉我。

关于javascript - 我如何将数据从组件A发送到组件B Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579307/

相关文章:

javascript - Alexa 技能 - sessionAttributes 实际上如何工作?

angular - 测试模块无法解析正在测试的模块 [Angular4、Karma、Jasmine]

dart - 如何在Dart中设置@RouteConfig

javascript - polymer 2.x : Wrapping external JS library in ES6 web component

javascript - Ruby on Rails View 通过渲染插入 js.erb 文件

javascript - 在 KonvaJS 上使用带有 globalCompositeOperation 的图像掩码?

javascript - react HOC : render hijacking with functional components

angular - 在 Angular 4 中使用 POST 时获得 200 状态但仍然出现错误

c# - ZedGraph 在 Visual Studio 2012 中不起作用

javascript - 在 React.js 中,我如何从组件的字符串表示形式呈现组件?