【问题标题】:Call a parent service get method from child custom element从子自定义元素调用父服务获取方法
【发布时间】:2020-04-24 10:54:20
【问题描述】:

我创建了一个使用角度元素的自定义 Web 组件,它需要在主应用程序 service.ts 中调用一个方法。

自定义元素

@Component({
      templateUrl: './sample.component.html',
      styleUrls: ['./sample.component.css']
   })
   export class SampleComponent{
   constructor(){
   //here i want to call the main application's service method.
   }
}

MainApplication.service.ts

@Injectable({
 providedIn: 'root'
})
export class StoreService {
   getData(): Observable<Model> {
   return this.dataSource.asObservable();
 }
}

我的问题是我想从自定义元素调用 getData()。前提是我已经在 MainApplication.component.ts 中引入了自定义元素。使用 eventEmitters 和 @Output 从自定义元素向父组件发送一些数据很容易,但是在调用可以提供一些数据作为回报的服务方法时,有什么办法吗?

【问题讨论】:

  • 我能想到的唯一方法是您必须将服务作为@Input() 传递给自定义元素,除了将服务绑定到窗口对象的一种非常hacky的方式
  • 尝试使用主题或行为主题
  • 您可以公开事件和可绑定属性。在父组件中,添加一个事件处理程序,在从服务获取数据后更新绑定到子组件的属性值。

标签: angular eventemitter angular-elements


【解决方案1】:

我知道这有点晚了,但是是的,你可以:

@Component({
      templateUrl: './sample.component.html',
      styleUrls: ['./sample.component.css']
   })
   export class SampleComponent{
   constructor(private storeService: StoreService){
       this.storeService.getData()
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2013-08-28
    • 2019-02-19
    • 2016-05-11
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多