繁体   English   中英

如何从类似于 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()testModelService.fetchModel()未收到 uuid 时会发生这种情况),因此是无缝的在这两种情况下处理。

也许您可以尝试使用Observable类的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());
  }
}

截至 2018 年 7 月和RxJS 6的发布,从值中获取 Observable 的新方法是导入of运算符,如下所示:

import { of } from 'rxjs';

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

of(someValue);

请注意,您过去必须像当前接受的答案一样执行Observable.of(someValue) 还有另RxJS一个很好的第6点的变化在这里

自 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()函数将在您的订阅者上被调用。

这就是为静态数据创建一个简单的 observable 的方法。

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 调用代替静态数据。

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

服务.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
        }
      }
}

组件.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM