使用共享服务处理输入和输出

时间:2017-10-16 20:23:52

标签: angular typescript

我正在重构两个组件之间有很多重复方法的代码。组件A是组件B的子组件,两者都可以是不同的实例,实际上它们应该是。我的问题是,在某些方法中我发出数据,当我在将方法传递给服务后尝试获取输入时,我无法将模板传递给模板。

我现在有这样的事情:

组件A和组件B正在发出事件,我没有改变这些方法,因为我无法分离该逻辑,如何更改服务端的输入并获取组件的更改?对此有何帮助?

component A 

export class CompA{
 template: ...
 ...
 inputs [
  'value1'
  'value2'
 ]
 outputs: [
 'doSomething'
 'doSomething2'
 'doSomething3'
 ] 

 public value1: string;
 public value2: string

 addLine(){
 //simple example
  if(this.value1 == ""){
   this.doSomething1.emit(3)

  // the functions are obviously bigger but i need this emit inside the service and catch the event in the component
  }
}

1 个答案:

答案 0 :(得分:0)

我不确定我理解这个问题。也许建立一个能够证明这个问题的傻瓜会对你有所帮助。

通常,如果您需要更新服务中的数据,只需设置值。

例如:

<强>服务

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

@Injectable()
export class ShareService {
   public data: string;

   setData(newdata : string){
       this.data = newdata;
   }

   clearData(){
       this.data = '';
   }
}

设置值的组件

export class PageA {
    constructor(private shareService: ShareService, private router: Router){
    }
    gotoPageB(){
        this.shareService.setData("Sample data");
        this.router.navigate(['pageb']);  
    }

}

获取值的组件

export class PageB {
    constructor(private shareService: ShareService){ }

    get somedata() : string {
      return this.shareService.data;
    }
}

这里的关键是在获取值的组件中使用getter属性(本例中为PageB),以便在数据服务值发生更改时随时更新。

这完全接近你的要求吗?

相关问题