如何使用 Angular 2 中服务类的单个实例更新 2 个组件中的数据 [英] How to update Data in 2 components using single instance of the Service Class in Angular 2

查看:18
本文介绍了如何使用 Angular 2 中服务类的单个实例更新 2 个组件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的服务类,其中有一个名为dataValue"的变量.

import { Injectable } from '@angular/core';@Injectable()导出类 DataService{构造函数(){console.log("新实例");}数据值:字符串=初始值";}

这是我的第一个组件,其中我使用我在该组件中定义的变量获取和初始化服务变量.并在组件变量上实现双向数据绑定.

import { Component } from '@angular/core';从'./dataservice'导入{数据服务};@成分({选择器:'第一个',模板:`<div>您的输入:<input type = "text" [(ngModel)] = "ChangeByFirstComponent">您输入了:{{ChangeByFirstComponent}}

`})导出类 FirstComponent {构造函数(私有_dataService:DataService){}ChangeByFirstComponent:字符串;获取数据值():字符串{返回 this._dataService.dataValue;}设置数据值(ChangeByFirstComponent){{this._dataService.dataValue = this.ChangeByFirstComponent;}}

这里是我的第二个组件,在这里做同样的事情,就像 firstcomonent

import { Component } from '@angular/core';从'./dataservice'导入{数据服务};@成分({选择器:'第二',模板:`<div>您的输入:<input type = "text" [(ngModel)] = "ChangeBySecondComponent">您输入了:{{ChangeBySecondComponent}}

`})导出类 SecondComponent {构造函数(私有_dataService:DataService){}ChangeBySecondComponent:字符串;获取数据值():字符串{返回 this._dataService.dataValue;}设置数据值(ChangeByFirstComponent){this._dataService.dataValue = this.ChangeBySecondComponent;}}

我想要的功能是,如果用户从第一个组件输入某些内容,由于服务类的单个实例,第二个组件将太快地获得更改

解决方案

您可以通过使用 BehaviorSubject 来实现此类功能.当第一个组件发生更改时,您可以将该更改推送到 BehaviorSubject,然后 subscribe 到第二个组件中的更改,因此它会在第一个组件中出现更改时获取更改.你可以这样做,

import { Injectable } from '@angular/core';@Injectable()导出类 DataService{数据主题:行为主题;构造函数(){this.dataSubject = new BehaviorSubject(null);console.log("新实例");}pushChanges(数据值){this.dataSubject.next(dataValue);}getChanges() {返回 this.dataSubject.asObservable();}数据值:字符串=初始值";}

在你的第一个组件中,你可以写,

this._dataService.pushChanges(this.ChangeByFirstComponent);

在你的第二个组件中,

this._dataService.getChanges().subscribe(changeByFirstComponent =>{//只有在第一个组件发生变化时才会触发此方法//它被推送到 `dataSubject`console.log(changeByFirstComponent);})

您可以重复此过程,您也需要反向功能.

This is my service class in which i have one variable called " dataValue".

import { Injectable } from '@angular/core';
@Injectable()
export class DataService 
{
 constructor() 
{
console.log("new instance");
  }
 dataValue: string = "initial value";
}

Here it is my first component in which i am getting and intializing the service variable with the variable i define in this component.and implementing two way data binding on component variable.

import { Component } from '@angular/core';
import { DataService } from './dataservice';

@Component({
selector: 'first',

 template: `
                 <div>
                        Your Input : <input type = "text" [(ngModel)] = "ChangeByFirstComponent">
                        You Entered : {{ChangeByFirstComponent}}
                 </div>   
                `
})
export class FirstComponent {
constructor(private _dataService: DataService) { }

ChangeByFirstComponent: string;

get DataValue(): string {
return this._dataService.dataValue;
 }

 set DataValue(ChangeByFirstComponent){
 {
  this._dataService.dataValue = this.ChangeByFirstComponent;
  }
}

and here it is my second component , doing the same thing here just as firstcomonent

import { Component } from '@angular/core';
import { DataService } from './dataservice';

@Component({
    selector: 'second',
    template: `
                 <div>
                        Your Input : <input type = "text" [(ngModel)] = "ChangeBySecondComponent">
                        You Entered : {{ChangeBySecondComponent}}
                 </div>  ` 

})

export class SecondComponent {
    constructor(private _dataService: DataService) { }
    ChangeBySecondComponent: string;

    get DataValue(): string {
        return this._dataService.dataValue;
    }

    set DataValue(ChangeByFirstComponent) {
        this._dataService.dataValue = this.ChangeBySecondComponent;
    }
}

i want the functionality like if the user input something from first component, the second component will get the change too rapidly due to single instance of the service class

解决方案

You can achieve this type of functionality by using BehaviorSubject. When there is a change in first component you can push that change to BehaviorSubject and then subscribe to that in second component, so it gets the changes as they appear in first component. You can do something like this,

import { Injectable } from '@angular/core';
@Injectable()
export class DataService 
{
 dataSubject: BehaviorSubject;
 constructor() 
{
this.dataSubject = new BehaviorSubject(null);
console.log("new instance");
  }
pushChanges(dataValue) {
  this.dataSubject.next(dataValue);
}
getChanges() {
  return this.dataSubject.asObservable();
}
 dataValue: string = "initial value";
}

In your first component, you can write,

this._dataService.pushChanges(this.ChangeByFirstComponent); 

And in your second component,

this._dataService.getChanges().subscribe( 
changeByFirstComponent => {   

  // this method will be triggered only when there is change in first component 
  // and it's pushed on the `dataSubject`

  console.log(changeByFirstComponent);
}
)

You can repeat this process, you want the reverse functionality too.

这篇关于如何使用 Angular 2 中服务类的单个实例更新 2 个组件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆