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

时间:2019-08-27 06:27:09

标签: angular typescript angular2-services

我正在尝试从服务类中调用组件方法,但出现类似“ ERROR TypeError:无法读取未定义的属性” test”的错误。但是我也遇到过类似的问题,但其中大部分都解释了组件之间的调用,因此我理解不正确。

示例: Testcomponent.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)

2 个答案:

答案 0 :(得分:0)

尝试以下代码。供参考,请访问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);
  }
}

答案 1 :(得分:0)

您应该像这样导入主题,并应该使用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);
    });

  }
}