簡體   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