【问题标题】:Call Component Function from Service从服务调用组件函数
【发布时间】:2019-08-22 13:09:09
【问题描述】:

我正在尝试为我的应用程序创建一个文件上传组件。最后,当文件上传完成时,我想清除上传的文件,为此我在文件上传器组件中编写了波纹管函数。

  clearFileList(){
    this.uploadedFiles=[]
  }

现在我想从服务中调用这个函数,之后在服务的帮助下可以在其他组件中重用该方法。

我该怎么做。

【问题讨论】:

    标签: angular typescript angular-services angular-components


    【解决方案1】:

    从服务调用组件函数不是最好的模式。我建议一些不同的东西。服务应该包含公共主题并且组件应该订阅它:

    class Service {
      public stream$ = new Subject<any>();
    
      method() {
        this.stream$.next(...);
      }
    
    }
    
    class Component {
      constructor(private service: Service) {}
    
      onInit() {
        this.service.stream$.subscribe(data => {
          this.method(data);
        }
      }
      method() {
        // do stuff;
      }
    
    }
    

    您可以从服务中调用method,这将调用组件方法。

    当然还要记得退订。

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 2021-10-29
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 2019-01-20
      • 2012-07-16
      相关资源
      最近更新 更多