【问题标题】:How to call a function in a component from service directly?如何直接从服务调用组件中的函数?
【发布时间】:2019-05-30 23:47:31
【问题描述】:

是否有任何选项可以直接从服务中执行组件中的方法?

@Component({
  selector:'component'
})
export class Component{
  function2(id){ 
    console.log('ID printed '+ id);
  }
}


@Injectable()

export class Service {
  callfunction2() {
    //how?;
      }
}

【问题讨论】:

  • 不,因为这与组件和服务的交互方式相反(组件应该调用服务,反之亦然)。
  • 技术上可以使用注射器,但不要这样做(原因在上面的评论中列出)
  • 任何替代解决方案???

标签: angular typescript angular-services


【解决方案1】:

您不应该从服务中调用组件函数。

但是,您可以在服务中创建一个主题,并从组件中订阅它。

在这种情况下,一旦 callfunction2 被传递,它就会在 Subject 上发出 id 值,并且订阅此 Subject 的任何组件都将收到该值

@Component({
  selector:'component'
})
export class Component{

  constructor(private service: Service) {}

  function2(id){
    this.service.subject.subscribe(id => {
        console.log('ID printed ' + id);
    });
  }
}


@Injectable()

export class Service {

  public subject: Subject<any> = new Subject<any>();

  callfunction2(id) {
    this.subject.next(id);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 2017-05-26
    • 1970-01-01
    • 2012-12-19
    • 2014-04-08
    • 2017-04-10
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多