简体   繁体   English

如何在 Angular 2 中创建 RxJS 主题?

[英]How to create RxJS subject in Angular 2?

I am able to create an Observable in my angular component in below mentioned way我可以通过下面提到的方式在我的 angular 组件中创建一个 Observable

...
...
import { Observable } from 'rxjs/Observable';
..
...
let observable = new Observable( function subscribe(observer) {
        observer.next(1);
        observer.next(2);
        observer.next(3);
        observer.next(4);
        setTimeout(() => {observer.next(5); },9000);
    });

But am not aware of how to create a Subject, can some one provide an example for the same?但是我不知道如何创建一个主题,有人可以提供一个相同的例子吗?

Here's a plunker: http://plnkr.co/edit/jLtFLjWrvHGI0ZPHl10B?p=preview 这是一个吸烟者: http ://plnkr.co/edit/jLtFLjWrvHGI0ZPHl10B?p = preview

import {Subject} from 'rxjs/Subject';

@Injectable()
export class MyService {

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

    constructor() {}
}

subscribe to it like an observable: 订阅它就像一个可观察的:

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

and push values to it like an observable again with next 并将值推送到它,就像下一个再次观察一样

  ngAfterViewInit(){
      this._myService.invokeEvent.next(1);
  }

Using Rx.Subject with Angular it is no different from using it without Angular , the main principle is the same, look at the example below 使用Rx.Subject角度是没有使用它没有不同,其主要原理是一样的,看下面的例子

const subject = new Rx.Subject();
const subscription = subject.subscribe(
  (data) => console.log(data),
  (err) => console.log(err),
  () => console.log('Completed')
);

subject.next(1);
subject.next(2);
subject.next(3);
subject.complete();
<script src="https://unpkg.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>

You need to make new instance Rx.Subject , then subscribe to it where you need to, and fire event. 您需要创建新的实例Rx.Subject ,然后在您需要的地方订阅它,并触发事件。

You can do it by following code您可以通过以下代码来完成

 import { BehaviorSubject } from 'rxjs'; subject = new BehaviorSubject<string>(""); observer = this.subject.asObservable(); //TO FIRE NEXT EVENT this.subject.next("My next value"); // TO SUBSCRIBE EVENT this.observer.subscribe({ next: (value)=>{ console.log(value); // will return My next value } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM