从共享服务中调用组件的功能

时间:2017-04-11 02:02:44

标签: angular typescript angular2-services

我正在尝试使用共享服务建立兄弟通信。我首先向您展示相关组件:

父组件:

import { SerializationService } from './serialization/serialization.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [SerializationService]
})
export class AppComponent implements OnInit {
    //irrelevant body
}

共享服务:

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

@Injectable()
export class SerializationService {

    serialize() {
         //NEED TO CALL getData() IN DataComponent!!!
    }
}

两个兄弟组成部分:

//Toolbar component: 
import { SerializationService } from '../serialization/serialization.service';

@Component({
  selector: 'toolbar-component',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.css']
})
export class ToolbarComponent {

  constructor(private serializationService : SerializationService) { }

  serialize() {
      this.serializationService.serialize();
  }
}

//Data Component: 
import { SerializationService } from "../serialization/serialization.service";

@Component({
  selector: 'pixi-component',
  templateUrl: './pixi.component.html',
  styleUrls: ['./pixi.component.css'],
})
export class DataComponent {

    private data : String;

    constructor(private operationService: OperationService, 
                private serializationService : SerializationService
    ){}

    getData() : String {
        return this.data;
    }
}

您可以看到ToolbarComponent调用serialize()的{​​{1}}函数。该服务需要一些数据来序列化,因此需要从SerializationService调用getData()函数并捕获它的返回。这两个组件都是DataComponent的孩子(他们是兄弟姐妹)。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

从服务调用组件的方法不是一个好主意,也许甚至不可能。您的组件使用服务,而不是相反。

但是你可以从DataComponent获取数据到ToolbarComponent,例如通过使用模板引用变量引用兄弟并使用例如TollbarComponent中的输入来接收数据:

app.component.html:

<toolbar-component [dataToSerialize] = "#dataComponent.getData()"></toolbar-component>
<pixi-component #dataComponent></pixi-component>

然后,您可以在ToolbarComponent的序列化方法中将数据传递给SerializationService:

export class ToolbarComponent {

    constructor(private serializationService : SerializationService) { }
     @Input() dataToSerialize;

    serialize() {
        this.serializationService.serialize(this.dataToSerialize);
    }
}

根据应用程序的逻辑,您还可以在某些事件绑定上将数据传递给ToolbarComponent,例如在click事件上:

app.component.html:

<toolbar-component (click)="serialize(dataComponent.getData())"></toolbar-component>
<pixi-component #dataComponent></pixi-component>

//工具栏组件:

export class ToolbarComponent {

    constructor(private serializationService : SerializationService) { }

    serialize(data) {
        this.serializationService.serialize(data);
    }
}