【问题标题】:How to call a component method from service class - Angular如何从服务类调用组件方法 - Angular
【发布时间】:2019-08-27 06:27:09
【问题描述】:

我正在尝试从服务类调用组件方法,但收到类似“ERROR TypeError: Cannot read property 'test' of undefined”的错误。但是我遇到了类似的问题,但主要是解释组件到组件的调用,所以我理解不正确。

示例: 测试组件.ts

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

  test(){ 
    console.log('test method');
  }
}
测试服务.ts

@Injectable()

export class Testservice {

private testcomp: Testcomponent;

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

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

我在堆栈中浏览了这个 ref,但没有得到 How to call component method from service? (angular2) 的确切操作

【问题讨论】:

  • 我不确定这是否正确:不是。组件调用服务。反之则不然。如果您解释了您要解决的具体问题,我们可能会帮助您以更好的方式解决问题。
  • 这不是正确的做法。服务旨在从组件或其他服务中调用。为什么需要从服务中调用组件方法?
  • @JBNizet Ohh 如果这种方法不正确,那么我将尝试以另一种方式完成它。实际上在服务中我已经实现了一些合乎逻辑的东西..感谢您的澄清。
  • 我刚刚更新了@Tudor 在同一帖子stackoverflow.com/questions/40788458/… 中的回复。您会看到:1.- 一个服务有一个 observable 和一个方法。2.- 主订阅 observable,3.- 另一个组件调用 observable 的方法,使“可观察的变化”
  • 这不是一个正确的方法。您可以使用多个服务,它可以从另一个服务调用。服务用于组件到组件的交互。您需要注入服务才能在任何组件中使用它。

标签: angular typescript angular2-services


【解决方案1】:

试试下面的代码。参考请访问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);
  }
}

【讨论】:

    【解决方案2】:

    您应该像这样导入主题,并且应该使用 next 从服务中发出您的值。

    @Injectable()
    import { Subject } from 'rxjs';
    
    export class Testservice {
    
      messageSubject = new Subject();
    
    
    // service method
    dummy(){
          this.messageSubject.next('hello from service'); // emit event
      }
    }
    

    并像这样在您的组件中订阅事件:

    @Component({
      selector:'component'
    })
    import {Testservice}  from 'testservice';
    export class Testcomponent{
            constructor(private testservice:Testservice) {  // import service
       }
    
      test(){ 
      this.testservice.messageSubject.subscribe((message)=>{
       console.log(message);
        });
    
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2020-10-24
      • 1970-01-01
      • 2020-10-29
      相关资源
      最近更新 更多