在 angular 4 中的一个组件与另一个组件之间共享数据 [英] Sharing data between one compoent to another component in angular 4

查看:30
本文介绍了在 angular 4 中的一个组件与另一个组件之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将布尔值从父 component.ts 更改为子 component.ts想使用 ngif 显示和隐藏登录和注销选项但不起作用.我不知道如何在两个组件之间设置和共享布尔值.我正在使用 templateUrl.

app.component.ts:

导出类 AppComponent {公共是有效的:布尔值;构造函数(私有路由器:路由器){}登出(){localStorage.removeItem('email');this.router.navigate(['./login']);this.isValid=true;}}

登录.component.ts

导出类 LoginComponent 实现 OnInit {公共用户名:字符串;公共密码:字符串;构造函数(私有路由器:路由器){}ngOnInit() {}用户登录(表单:NgForm){if(form.value.username==="admin@gmail.com" && form.value.password==="admin"){localStorage.setItem('email',form.value.username);this.router.navigate(['./php']);this.isValid=false;//不工作//} } }

app.component.html

解决方案

在缺乏直接连接的组件之间传递数据时,例如兄弟、孙子等,您应该使用共享服务.您可以使用 RXJS BehaviorSubjectSubject 用于跨组件通信.
主体与行为主体

创建服务

import { Injectable } from '@angular/core';从'rxjs/BehaviorSubject'导入{BehaviorSubject};@Injectable()导出类 SharedService {private valueSource = new BehaviorSubject(false);currentValue = this.valueSource.asObservable();构造函数(){}更改值(值:布尔值){this.valueSource.next(value)}}

使用 Angular 模块注册服务.

<块引用>

为什么?如果我们希望全局共享依赖项的实例并且在我们配置它的应用程序中共享 stateNgModule.

来自 Angular文档

<块引用>

Angular 模块提供者 (@NgModule.providers) 注册到应用程序的根注入器.Angular 可以注入对应的它创建的任何类中的服务.一旦创建,一个服务实例为应用程序的生命而生,Angular 注入了这一服务实例在每个需要它的类中.

@NgModule({声明: [应用组件,],进口:[浏览器模块,浏览器动画模块,],提供者:[共享服务],引导程序:[AppComponent],

在组件中注入 SharedService
app.component.ts:

导出类 AppComponent {公共 isValid:boolean;构造函数(私有路由器:路由器:私有服务:SharedService){this.service.currentValue.subscribe(message => this.isValid = message);//订阅currentValue observable.}登出(){localStorage.removeItem('email');this.router.navigate(['./login']);this.isValid=true;}

login.component.ts

导出类 LoginComponent 实现 OnInit {公共用户名:字符串;公共密码:字符串;公共是有效的:布尔值;构造函数(私有路由器:路由器,私有服务:SharedService){}ngOnInit() {}用户登录(表单:NgForm){if(form.value.username==="admin@gmail.com" && form.value.password==="admin"){localStorage.setItem('email',form.value.username);this.router.navigate(['./php']);this.isValid=false;this.service.changeValue(this.isValid);//它在BehaviorSubject上调用next来改变它的值.} } }

How to change boolean value from parent component.ts to child component.ts want to show and hide the login and logout option using ngif but not working.I do not know how to set and share boolean value between two components. I am using templateUrl.

app.component.ts:

export class AppComponent { 
public isValid:boolean;
constructor(private router:Router){ 
} 
 logout(){
 localStorage.removeItem('email');
 this.router.navigate(['./login']);
 this.isValid=true; 
 } 
 }

login.component.ts

export class LoginComponent implements OnInit {
public username:string;
public password:string; 
constructor(private router:Router) { } 
ngOnInit() {
} 
userLogin(form:NgForm){ 
if(form.value.username==="admin@gmail.com" && form.value.password==="admin")
 {
  localStorage.setItem('email',form.value.username);
  this.router.navigate(['./php']);
  this.isValid=false;//not working//
} }  }

app.component.html

<ul class="nav navbar-nav navbar-right">
  <li *ngIf="isValid">
    <a [routerLink]="['/login']" >Login</a>
  </li>

  <li *ngIf="!isValid">
      <a (click)="logout()">LogOut</a>
    </li>

</ul>

解决方案

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should use a shared service. You could either use RXJS BehaviorSubject or Subject for cross component communication.
Subject vs BehaviorSubject

Create a Service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

    @Injectable()
    export class SharedService {

      private valueSource = new BehaviorSubject<boolean>(false);
      currentValue = this.valueSource.asObservable();

      constructor() { }

     changeValue(value: boolean) {
        this.valueSource.next(value)
      }

    }

Register the service with an Angular module.

why? If we want an instance of a dependency to be shared globally and share state across the application we configure it on the NgModule.

from Angular docs

Angular module providers (@NgModule.providers) are registered with the application's root injector. Angular can inject the corresponding services in any class it creates. Once created, a service instance lives for the life of the app and Angular injects this one service instance in every class that needs it.

@NgModule({
      declarations: [
        AppComponent,


      ],
      imports: [

        BrowserModule,
        BrowserAnimationsModule,

      ],
      providers: [SharedService],
      bootstrap:[AppComponent],

Inject the SharedService in the components
app.component.ts:

export class AppComponent { 
public isValid:boolean;
constructor(private router:Router:private service:SharedService){ 
       this.service.currentValue.subscribe(message => this.isValid = message);//subscribe to the currentValue observable.
} 
 logout(){
 localStorage.removeItem('email');
 this.router.navigate(['./login']);
 this.isValid=true;
 } 

login.component.ts

export class LoginComponent implements OnInit {
public username:string;
public password:string; 
public isValid:boolean;
constructor(private router:Router,private service:SharedService) {}


ngOnInit() {
} 
userLogin(form:NgForm){ 
if(form.value.username==="admin@gmail.com" && form.value.password==="admin")
 {
  localStorage.setItem('email',form.value.username);
  this.router.navigate(['./php']);
  this.isValid=false;
  this.service.changeValue(this.isValid);//it calls next on the BehaviorSubject to change its value.
} }  }

这篇关于在 angular 4 中的一个组件与另一个组件之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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