字体角度可观察性:如何改变它的值? [英] Typescript Angular - Observable: how to change its value?

查看:22
本文介绍了字体角度可观察性:如何改变它的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我错过了什么。我找不到有关可观察对象及其语法的简单教程。我正在使用角度,我需要从服务调用一个函数(在组件中定义)。我读到了这个solution。但是我想不出如何更改服务中创建的观察值(可能创建不是最好的方法)。

我有一个类似于解决方案中的组件:

@Component({
  selector: 'my-component',
  ...
)}
export class MyComponent {
   constructor(myService:MyService) {
   myService.condition.subscribe(value => doSomething(value));
}

doSomething(value) {
  if (value) // do stuff
  else // other stuff
}

}

这是我的服务:

import { Injectable } from '@angular/core';
import { Observable} from 'rxjs/Observable';

@Injectable()

export class MyService {
    private condition: Observable<boolean>;
    constructor() { 
       this.condition= new Observable(ob => {ob.next(false); })
       // maybe ob.next is not the best solution to assign the value?
    }

    change() {// how can i change the value of condition to 'true', to call
              // the doSomething function in the component?? 
    }

}

推荐答案

my other answer(由于可能对某人有帮助而保留)的评论中,您似乎希望利用某物的力量来随时间发送值

正如DOMZE建议的那样,使用一个主题,但是这里有一个(很简单的)示例,展示了如何可以做到这一点。虽然显然有some pitfalls to avoid in using Subject directly,但这由您决定。

import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { Observable, Subject } from 'rxjs/Rx';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Open the console.</h2>
    </div>
  `,
})
export class App {

  constructor() {}

  let subject = new Subject();

  // Subscribe in Component
  subject.subscribe(next => {
    console.log(next);
  });

  setInterval(() => {
    // Make your auth call and export this from Service
    subject.next(new Date())
  }, 1000)
}

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

Plunker

以我的拙见,对于此场景,我不明白为什么简单的Service/Observable不够用,但这不关我的事。

进一步阅读:Angular 2 - Behavior Subject vs Observable?

这篇关于字体角度可观察性:如何改变它的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆