为什么订阅函数不会在角度2中调用?

时间:2016-12-20 07:14:53

标签: angularjs angular rxjs

我在角度中使用了observable。实际上我的问题是当我点击按钮我的subscribe函数没有调用为什么? 根据文档subscribe,当我们调用next函数

时,函数会调用

https://plnkr.co/edit/83NaHoVaxiXAeUFoaEmb?p=preview

constructor() {
  this.data = new Observable(observer => this.dataObserver = observer);
  this.data.subscribe(value => {
    console.log('+++')
    console.log(value)
  })
}

hndle(){
  this.name.push({name:"navee"});

  this.dataObserver.next(this.name);
}

这里是文档

http://reactivex.io/rxjs/manual/tutorial.html

3 个答案:

答案 0 :(得分:1)

根据Volodymyr Bilyachat的建议,我修改了你的代码。它的工作现在plz检查。问题在于您使用dataObserver

的方式
     //our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <ul>
      <li *ngFor ="let n of name">{{n.name}}</li>
      </ul>
      <button (click)="hndle()">heelo</button>
    </div>
  `,
})
export class App {
  private data:Observable;
  private dataObserver:Observer;
  name:string;
  name[];
  constructor() {
        this.dataObserver = new Observable(observer => this.dataObserver = observer);
 this.dataObserver.subscribe(value => {
    console.log('+++')
    console.log(value)
  });
  }

  hndle(){

    this.name.push({name:"navee"});

    this.dataObserver.next(this.name);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

链接https://plnkr.co/edit/PO80y2udrOhsVq4QQXc5?p=preview

答案 1 :(得分:0)

在您的情况下,最好使用此解决方案:

constructor() {
    this.data = new Subject();

    this.data.subscribe(value => {
        console.log('+++');
        console.log(value);
    });
}

hndle() { // TYPO: Probably it was meant to be handle
    this.name.push({ 
        name: 'navee'
    });

    this.data.next(this.name);
}

不要忘记添加:

import { Subject } from 'rxjs/Subject'

工作示例:

https://plnkr.co/edit/zB8FHTVEm2QUHiEAYuQB?p=preview

答案 2 :(得分:0)

我相信你订阅了2次观察。您应该可以通过添加.share()

来修复它
constructor() {

    this.data = new Observable(observer => this.dataObserver = observer).share();
   this.data.subscribe(value => {
    console.log('+++')
    console.log(value)

  })
  }

  hndle(){
    this.name.push({name:"navee"});

    this.dataObserver.next(this.name);
  }