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<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??
    }

}

原文由 Johannes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 849
2 个回答

我的其他答案 的评论(保留,因为它可能对某人有帮助),您似乎想利用某些东西的力量 随着时间的推移 发出值。

正如 DOMZE 建议的那样,使用主题,但这里有一个(简单的)示例,展示 了如何 做到这一点。尽管 直接使用 Subject 显然有一些陷阱要避免,但我将把它留给你。

 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 {}

普朗克

以我的拙见,对于这种情况,我不明白为什么简单的 Service/Observable 是不够的,但这不关我的事。

进一步阅读: Angular 2 - 行为主体与可观察?

原文由 msanford 发布,翻译遵循 CC BY-SA 3.0 许可协议

管理登录状态

对于此实现,您只需要一个服务。在其中,您将发出后端请求以查看用户是否有会话,然后您可以将其保存在服务的类变量中。然后,如果设置了该变量,则返回该变量,或者直接返回 REST 调用的结果。

例如:

 export class AuthenticationService {

 private loggedIn: boolean = null;

 constructor(private http: Http) { }

 getUserSession(credentials): Observable<boolean> {

  if (this.loggedIn !== null) {

    return Observable.of(this.loggedIn);

  } else {

    return this.http.get('/authenticate?' + credentials)
      .map((session: Response) => session.json())
      .catch(e => {
        // If a server-side login gate returns an HTML page...
        return Observable.of(false);
      });

  }
}

然后在组件中,像往常一样订阅 Observable 并按需对其进行操作。

还有其他方法可以使用 Observable.share()Observable.replay()

可观察语法

要回答有关 Angular2 中 Rx Observable 语法的部分问题(如果有人谷歌它),通用形式是:

在服务中:

 return this.http.get("/people", null)
  .map(res.json())
  .catch(console.error("Error in service")

在一个组件中,例如:

 this.someService.getPeople()
  .subscribe(
    people => this.people,
    error => console.warn('Problem getting people: ' + error),
    () => this.doneHandler();
  );

正式地:

 interface Observer<T> {
  onNext(value: T) : void
  onError(error: Error) : void
  onCompleted() : void
}

当接收到“下一个”值时调用第一个函数。对于 REST 调用(最常见的情况),它包含整个结果。

第二个函数是一个错误处理程序(在服务中调用 Observable.trow() 的情况下)。

最后一个在结果集有时被调用,并且不带任何参数。这是您可以调用 doSomething() 函数的地方。

原文由 msanford 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进