如何从类似于 Angular 中的 http 的静态数据创建 Observable?

How to create an Observable from static data similar to http one in Angular?

我有一个服务有这个方法:

export class TestModelService {

    public testModel: TestModel;

    constructor( @Inject(Http) public http: Http) {
    }

    public fetchModel(uuid: string = undefined): Observable<string> {
        if(!uuid) {
            //return Observable of JSON.stringify(new TestModel());
        }
        else {
            return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
                .map(res => res.text());
        }
    }
}

在组件的构造函数中,我是这样订阅的:

export class MyComponent {
   testModel: TestModel;
   testModelService: TestModelService;

   constructor(@Inject(TestModelService) testModelService) {
      this.testModelService = testModelService;

      testService.fetchModel("29f4fddc-155a-4f26-9db6-5a431ecd5d44").subscribe(
          data => { this.testModel = FactModel.fromJson(JSON.parse(data)); },
          err => console.log(err)
      );
   }
}

如果一个对象来自服务器,这会起作用,但我正在尝试创建一个可观察对象,它将与给定的 subscribe() 静态字符串调用一起工作(当 testModelService.fetchModel() 没有收到时会发生这种情况一个 uuid),所以在这两种情况下都可以无缝处理。

也许您可以尝试使用 Observable class 的 of 方法:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

自从 Angular 2.0.0

以来,情况似乎发生了变化
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

将在您的订阅者上调用 .next() 函数。

这是为静态数据创建简单可观察对象的方法。

let observable = Observable.create(observer => {
  setTimeout(() => {
    let users = [
      {username:"balwant.padwal",city:"pune"},
      {username:"test",city:"mumbai"}]

    observer.next(users); // This method same as resolve() method from Angular 1
    console.log("am done");
    observer.complete();//to show we are done with our processing
    // observer.error(new Error("error message"));
  }, 2000);

})

to subscribe to it is very easy

observable.subscribe((data)=>{
  console.log(data); // users array display
});

希望这个回答对您有所帮助。我们可以使用 HTTP 调用来代替静态数据。

自 2018 年 7 月和 RxJS 6 发布以来,从值获取 Observable 的新方法是像这样导入 of 运算符:

import { of } from 'rxjs';

然后根据值创建可观察对象,如下所示:

of(someValue);

请注意,您过去必须像当前接受的答案中那样做 Observable.of(someValue)。有一篇关于 RxJS 6 其他变化的好文章 here.

通过这种方式,您可以从数据创建 Observable,在我的例子中,我需要维护购物车:

service.ts

export class OrderService {
    cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
    cartItems$ = this.cartItems.asObservable();

    // I need to maintain cart, so add items in cart

    addCartData(data) {
        const currentValue = this.cartItems.value; // get current items in cart
        const updatedValue = [...currentValue, data]; // push new item in cart

        if(updatedValue.length) {
          this.cartItems.next(updatedValue); // notify to all subscribers
        }
      }
}

Component.ts

export class CartViewComponent implements OnInit {
    cartProductList: any = [];
    constructor(
        private order: OrderService
    ) { }

    ngOnInit() {
        this.order.cartItems$.subscribe(items => {
            this.cartProductList = items;
        });
    }
}

自 2021 年 5 月起,从值获取 Observable 的新方法是:

导入:

import "rxjs/add/observable/of"
import { Observable } from "rxjs/Observable"

并像这样使用::

Observable.of(your_value)