当订阅

当订阅

问题描述:

时,主题会发出一个值如何让订阅者在订阅时发出一个值?当订阅

let mySubject = new Subject<string> 
// specify somehow that when you subscribe to mySubject, it emits 'foo' 

mySubject.subscribe(value => { 
    // get 'foo' here 
}); 
+3

根据您的使用情况(无法真正从问题推断出),“BehaviorSubject” - 作为初始值 - 或ReplaySubject - 重播指定数量的最新值。 – cartant

+0

这就是答案。 '使用行为主题'' – Skeptor

你只需要数据使用.next

现在推到流下面的代码应该工作:

const mySubject = new Subject() 

mySubject.subscribe(value => { 
    console.log(value) 
}); 

mySubject.next("foo") 

您不仅可以从Subject其实你散发出流/值可以将流/值发送到多个Observers。这意味着你可以附加多个观察者到Subject。每个Subject可以包含Observer的集合。当你订阅那个主题时,它会向其集合中的每个观察者发送流/值。

const subject = new Rx.Subject() 
// add an observer to the list of observers of the subject 
const sub1 = subject.subscribe(function(val){ 
     console.log("observer 1", val); 
}); 
// add another observer to the list of observers of the subject 
const sub2 = subject.subscribe(function(val){ 
     console.log("observer 2", val); 
}); 
// notify all observers in the list with "hi there" 
subject.next('hi there'); 

// remove observer1 from the list 
sub1.unsubscribe(); 

不仅如此,您可以使用Subject作为Observer并将其提供给Observable。这意味着您可以使用主题将Observable“多播”到多个观察者。

// To "share" the observable tick$ with two observers, 
// this way, we can pipe all notifications 
// through a Subject, like so 

const tick$ = Rx.Observable.interval(1000); 
const subject = new Rx.Subject(); 
subject.subscribe(function(val){ 
    console.log('from observer 1: '+ val); 
}); 
subject.subscribe(function(val){ 
    console.log('from observer 2: '+ val); 
}); 
tick$.subscribe(subject); 

为了了解RxJs你已经了解Observer Pattern通过“Gang Of Four”规定。我会建议你尝试理解观察者模式,我希望你能清楚地知道RxJs库在做什么。

还有另外一个精彩的reference来自Learning JavaScript Design PatternsAddy Osmani

我相信你,你希望有什么样的描述实际上是你不希望有什么..

举例来说,如果你希望你受到每一个有人订阅它的时候发出富,那么你就可以延长学科。

https://jsfiddle.net/v11rndmt/

class MySubject extends Rx.Subject{ 
    constructor(){ super(); } 
    subscribe(oOrOnNext, onError, onCompleted){ 
    const subs = super.subscribe(oOrOnNext, onError, onCompleted); 
    this.next("foo") 
    return subs; 
    } 
} 

let sub = new MySubject() 
sub.subscribe(v => console.log(v)); 
sub.subscribe(v => console.log(v)); 
sub.subscribe(v => console.log(v)); 

这将发射foo的3倍。第一次只有一个用户,所以它会打印一次。第二次有两个,所以它会打印两次。第三个是3,所以它会打印3次。因此foo将被打印6次。

但我没有搞清楚这个用例。因此,也许你应该提供给我们更多的信息。