Angular 从可注入类调用组件函数

Angular 从可注入类调用组件函数,angular,cordova,ionic3,Angular,Cordova,Ionic3,我有一个可注入类和一个组件类。 我需要做的就是从可注入类调用组件类中的函数 可注射: Injectable() export class theInjected { constructor(private afAuth: AngularFireAuth, private googlePlus: GooglePlus, public alertCtrl: AlertController){ this.afAuth.authState.subscribe(user =>

我有一个可注入类和一个组件类。 我需要做的就是从可注入类调用组件类中的函数

可注射:

Injectable()
export class theInjected 
{

    constructor(private afAuth: AngularFireAuth, private googlePlus: GooglePlus, public alertCtrl: AlertController){

      this.afAuth.authState.subscribe(user => 
        {
          if(user) 
          {
            this.user = this.afAuth.authState; //this means alert('fire user logged in');

         //
         // I need to call the function here goTopage();
         //

          }
          else
          {
            Observable.of(null); //this means alert('fire user logged out');
          }
        }
      );
    }
}
@Component({
selector: 'home',
  templateUrl: 'home.html'
})

export class Home
{


constructor(public injected: theInjected){

}

  goTopage()
  {   
    this.navCtrl.setRoot(this.loggedInPage);
  }
}
组件:

Injectable()
export class theInjected 
{

    constructor(private afAuth: AngularFireAuth, private googlePlus: GooglePlus, public alertCtrl: AlertController){

      this.afAuth.authState.subscribe(user => 
        {
          if(user) 
          {
            this.user = this.afAuth.authState; //this means alert('fire user logged in');

         //
         // I need to call the function here goTopage();
         //

          }
          else
          {
            Observable.of(null); //this means alert('fire user logged out');
          }
        }
      );
    }
}
@Component({
selector: 'home',
  templateUrl: 'home.html'
})

export class Home
{


constructor(public injected: theInjected){

}

  goTopage()
  {   
    this.navCtrl.setRoot(this.loggedInPage);
  }
}
我只是想要一种从可注入类调用组件类中存在的函数的方法


谢谢

使用一个可观察对象并在组件中订阅它

export class theInjected 
{
  observable = new BehaviorSubject();

  someMethod() {
    this.observable.next('foo');
  }
}

可能的重复不是重复,这是一个不同的方法尝试冈特建议现在!可能是XY问题。不清楚为什么goTopage应该在组件而不是服务中定义。@estus,因为它应该在组件中定义。this.navCtrl.setRoot(this.loggedInPage);不具有任何效果(不改变页面)的情况下,其用于注射。。。它必须用于组件本身。这不是一种解释。如果必须在组件中使用它,则可以在注入到组件的服务中定义它。在值更改之前(在此运行this.observable.next('foo');`injected.observable.subscribe(val=>this.goTopage());从custructor调用函数goTopage()`如果您不希望使用
Subject
替换
BehaviorSubject
BehaviorSubject
立即将其当前值发送给新订户。这有助于避免在接收器有机会订阅之前发出事件时出现计时问题。您好,我按照实现的那样做了,但是它没有调用函数goToPage()。这是home.ts构造函数中的代码:
injected.observable.subscribe(val=>This.goToPage())
需要调用的代码末尾的injected:
this.observable.next('a')及其定义为
可观察=新主题()