Angular2从服务调用组件

时间:2016-11-03 04:28:09

标签: javascript angular typescript rxjs observable

我正试图通过ComponentService中调用方法。这样做的正确方法是什么?我曾尝试使用rxjs Subject创建一个Observable,但我无法解决它。

import {Subject} from 'rxjs/Subject';
    export class MyService {
        callComponent = function(value) {

            let invokeEvent = new Subject();

            invokeEvent.next({some:value})
        }
    }

和我的组件

export class MyComponent {
    constructor(private _myService: MyService) {
             this._myService.invokeEvent.subscribe(value => console.log(value))
           }

}

3 个答案:

答案 0 :(得分:2)

以上是这个问题:http://plnkr.co/edit/WKSurRJMXo5JZOPrwSP5?p=preview

像这样更改您的服务

import {Subject} from 'rxjs/Subject';

@Injectable()
export class MyService {

    invokeEvent:Subject<any> = new Subject();


    callComponent(value) {
        this.invokeEvent.next({some:value})
    }
}

不要忘记在您的组件中提供

@Component({
  selector: 'my-component',
  template: `
  `,
  providers: [MyService]
})
export class MyComponent {
       constructor(private _myService: MyService) {
         this._myService.invokeEvent.subscribe(value => console.log(value));
         setTimeout(()=>{
            this._myService.callComponent(1);
         },1000);
       }
}

此外,如果您希望此服务成为全局共享服务;将(提供)它放在你的引导程序(旧)或ngModule中,这样它将在你的应用程序中共享相同的单例实例。

答案 1 :(得分:1)

您可以在服务中定义Observable,以便您可以从组件订阅该Observable。

// service

import { Injectable, Inject } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class MyService {
  private notify = new Subject<any>();
  /**
   * Observable string streams
   */
  notifyObservable$ = this.notify.asObservable();

  constructor(){}

  public notifyOther(data: any) {
    if (data) {
      this.notify.next(data);
    }
  }

  callComponent(value){
    this.notify.next({some:value});
  }
}

//元器件

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

import { MyService } from './my.service';
export class MyComponent {
  private subscription: Subscription;
  constructor( private _myService: MyService ){
  }

  ngOnInit() {
    this.subscription = this._myService.notifyObservable$.subscribe((value) => {
        console.log(value);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

答案 2 :(得分:0)

import {Subject} from 'rxjs/Subject';

export class MyService {

        private invokeEvent = new Subject(); 

        invokeEvent$ = this.missionConfirmedSource.asObservable();   //<<< this is important to declare invokeEvent with asObservable(); 

        callComponent = function(value) {
            invokeEvent.next({some:value})
        }
}


export class MyComponent {
    constructor(private _myService: MyService) {
             this._myService
                 .invokeEvent$                                        //<<< subscribe to invokeEvent$ to get the result
                 .subscribe(value => console.log(value))  
           }

}