angular - 如何从服务类调用组件方法 - Angular

标签 angular typescript angular2-services

我试图从服务类调用组件方法,但收到类似“错误类型错误:无法读取未定义的属性“测试””的错误。但我遇到了类似的问题,但主要是解释组件到组件的调用,所以我没有正确理解。

示例: 测试组件.ts

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

  test(){ 
    console.log('test method');
  }
}
Testservice.ts

@Injectable()

export class Testservice {

private testcomp: Testcomponent;

// service method
dummy(){
  //trying to call component method
  testcomp.test();
  }
}

这就是我的调用方式,我不确定这是否是正确的方法,所以任何人都可以让我了解如何从服务调用组件方法。

我在堆栈中浏览了这个引用,但没有得到到底在做什么 How to call component method from service? (angular2)

最佳答案

尝试以下代码。引用请访问https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

export class Testcomponent {

  constructor(private testService: Tesetservice) {
    this.testService.testComponent$.subscribe(res => {
      this.test()
    })
  }

  test() {
    console.log('test method');
  }
}

export class Testservice {

  private testComponentSource = new Subject<boolean>();

  // Observable string streams
  testComponent$ = this.testComponentSource.asObservable();


  // service method
  dummy() {
    //trying to call component method 
    this.testComponentSource.next(null);
  }
}

关于angular - 如何从服务类调用组件方法 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57668759/

相关文章:

angular - Angular2 的服务应该是无状态的吗?

node.js - 未捕获( promise ): Error: No provider for GooglePlus

javascript - 如何扩展 typescript 接口(interface)?

angular - 类型错误 : Object doesn't support property or method 'map' - AngularJS2

javascript - HTML5 : Attributes are not recognized after being added with JS/Jquery

javascript - package.json 中的 typescript 声明应该放在 "dependencies"、 "devDependencies"还是两者?

angular - 无法绑定(bind)到 'placeholder',因为它不是 'ng-multiselect-dropdown' 的已知属性

angular - NgRx 8 测试 provideMockStore - 状态切片的 setState

html - Angular Material 动画 - matRipple : escapes bounds of a div element

即使在包含 --aot --build-optimizer --sourcemaps=false 之后,Angular Production Build 仍然非常庞大