<legend id='u6hk1'><style id='u6hk1'><dir id='u6hk1'><q id='u6hk1'></q></dir></style></legend>
  • <tfoot id='u6hk1'></tfoot>
      <bdo id='u6hk1'></bdo><ul id='u6hk1'></ul>

  • <small id='u6hk1'></small><noframes id='u6hk1'>

      <i id='u6hk1'><tr id='u6hk1'><dt id='u6hk1'><q id='u6hk1'><span id='u6hk1'><b id='u6hk1'><form id='u6hk1'><ins id='u6hk1'></ins><ul id='u6hk1'></ul><sub id='u6hk1'></sub></form><legend id='u6hk1'></legend><bdo id='u6hk1'><pre id='u6hk1'><center id='u6hk1'></center></pre></bdo></b><th id='u6hk1'></th></span></q></dt></tr></i><div id='u6hk1'><tfoot id='u6hk1'></tfoot><dl id='u6hk1'><fieldset id='u6hk1'></fieldset></dl></div>

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

        How do i send data from component A to component B Angular 2(我如何将数据从组件 A 发送到组件 B Angular 2)
        <i id='U4IsH'><tr id='U4IsH'><dt id='U4IsH'><q id='U4IsH'><span id='U4IsH'><b id='U4IsH'><form id='U4IsH'><ins id='U4IsH'></ins><ul id='U4IsH'></ul><sub id='U4IsH'></sub></form><legend id='U4IsH'></legend><bdo id='U4IsH'><pre id='U4IsH'><center id='U4IsH'></center></pre></bdo></b><th id='U4IsH'></th></span></q></dt></tr></i><div id='U4IsH'><tfoot id='U4IsH'></tfoot><dl id='U4IsH'><fieldset id='U4IsH'></fieldset></dl></div>

            <tbody id='U4IsH'></tbody>
          • <legend id='U4IsH'><style id='U4IsH'><dir id='U4IsH'><q id='U4IsH'></q></dir></style></legend>

            • <bdo id='U4IsH'></bdo><ul id='U4IsH'></ul>
                  <tfoot id='U4IsH'></tfoot>

                  <small id='U4IsH'></small><noframes id='U4IsH'>

                  本文介绍了我如何将数据从组件 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Pause youtube video, youtube api(暂停 youtube 视频,youtube api)
                  Youtube iframe api not triggering onYouTubeIframeAPIReady(Youtube iframe api 未触发 onYouTubeIframeAPIReady)
                  How can I stop a video with Javascript in Youtube?(如何在 Youtube 中停止使用 Javascript 的视频?)
                  How to call Greasemonkey#39;s GM_ functions from code that must run in the target page scope?(如何从必须在目标页面范围内运行的代码中调用 Greasemonkey 的 GM_ 函数?)
                  How do you mute an embedded Youtube player?(如何使嵌入式 Youtube 播放器静音?)
                  How to get number of video views with YouTube API?(如何使用 YouTube API 获取视频观看次数?)

                    <legend id='uMfoS'><style id='uMfoS'><dir id='uMfoS'><q id='uMfoS'></q></dir></style></legend>

                    <small id='uMfoS'></small><noframes id='uMfoS'>

                        <i id='uMfoS'><tr id='uMfoS'><dt id='uMfoS'><q id='uMfoS'><span id='uMfoS'><b id='uMfoS'><form id='uMfoS'><ins id='uMfoS'></ins><ul id='uMfoS'></ul><sub id='uMfoS'></sub></form><legend id='uMfoS'></legend><bdo id='uMfoS'><pre id='uMfoS'><center id='uMfoS'></center></pre></bdo></b><th id='uMfoS'></th></span></q></dt></tr></i><div id='uMfoS'><tfoot id='uMfoS'></tfoot><dl id='uMfoS'><fieldset id='uMfoS'></fieldset></dl></div>
                        <tfoot id='uMfoS'></tfoot>
                          <bdo id='uMfoS'></bdo><ul id='uMfoS'></ul>

                            <tbody id='uMfoS'></tbody>