Typescript Angular - Observable:如何更改其值?
Typescript Angular - Observable:如何更改其值?
我可能漏掉了什么。我找不到一个关于Observable及其语法的简单教程。我正在使用Angular,我需要从服务中调用一个函数(在组件中定义)。我读了这个解决办法。但是我不知道如何更改在服务中创建的Observable的值(也许创建不是最好的方法)。
我有一个像解决方案中那样的组件:
@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; 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?? } }
admin 更改状态以发布 2023年5月23日
我想解释一下如何使用Observables,以便你想要更新该值,但我不会使用你的示例。我只会展示几行ES5代码,并附上解释。
var updateObservable; // declare here in order to have access to future function var observable = rx.Observable.create(function (observer) { observer.next(1); observer.next(2); observer.next(3); // attach a function to the variable which was created in the outer scope // by doing this, you now have your 'updateObservable' as a function and the reference to it as well // You will be able to call this function when want to update the value updateObservable = function (newValue) { observer.next(newValue); observer.complete(); }; }); // Suppose you want to update on click. Here actually can be whatever (event) you want vm.click = function () { // you can call this function because you have a reference to it // and pass a new value to your observable updateObservable(4); }; // your subscription to changes observable.subscribe(function(data) { // after 'click' event will be performed, subscribe will be fired // and the '4' value will be printed console.log(data); });
这里的主要思想是,如果您想要更新一个Observable的值,您必须在'create'函数内部进行此操作。如果您在此'create'函数中声明一个函数,则此操作将成为可能。
根据我其他回答的评论(保留下来可能对某些人有帮助),您似乎想利用某些内容的强大来随时间发出值。
正如DOMZE所建议的那样,使用一个主题,但是这里有一个(微不足道的)示例,展示了您如何做到这一点。尽管明显存在使用主题的一些要避免的问题,但我会把这个留给你来处理。
import { Component, NgModule } from '@angular/core' import { BrowserModule } from '@angular/platform-browser' import { Observable, Subject } from 'rxjs/Rx'; @Component({ selector: 'my-app', template: `Open the console.
`, }) 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 {}
在我谦逊的观点中,对于这种情况,我不明白为什么不使用简单的Service/Observable就不够了,但这不是我的事情。