角度|创建一个Observable不工作

时间:2018-06-12 14:20:40

标签: angular typescript observable

在Angular6中,我正在创建Injectable服务。我正在尝试初始化 Observable中的constructor,请参阅下面的简化代码。

问题: Observable.create的回调函数永远不会执行,也没有错误。为什么console.log('authObserver created!')从未被调用过?

import { Observable, Observer } from 'rxjs';

@Injectable()
export class UserLoginService implements OnInit{

  authObserver:Observer;
  authObservable:Observable;

  constructor() {
    this.authObservable = Observable.create((observer: Observer) => {
      this.authObserver = observer;
      console.log('authObserver created!')
    });  
  }    
}

randomCallbackFunction(){
  this.authObserver.next("Button has been clicked");
}

2 个答案:

答案 0 :(得分:4)

在您的代码中,我没有看到任何订阅发生。 Observable只在订阅后才能工作。试试这个

this.authObservable = Observable.create((observer: Observer) => {
      this.authObserver = observer;
      console.log('authObserver created!')
    });
this.authObservable.subscribe()

您可以看到它有效Here

答案 1 :(得分:1)

您需要订阅并密切注意通过下一步正确推送新值:

/*
 Create an observable that emits 'Hello' and 'World' on  
 subscription.
*/
 const hello = Rx.Observable.create(function(observer) {
    observer.next('Hello');
    observer.next('World');
 });

 //output: 'Hello'...'World'
  const subscribe = hello.subscribe(val => console.log(val));

看看这个Fiddle