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

后端 未结 5 1166
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 17:36

I am having a service that has this method:

export class TestModelService {

    public testModel: TestModel;

    constructor( @Inject(Http) public http: Ht         


        
相关标签:
5条回答
  • 2020-12-12 18:10

    This is how you can create a simple observable for static data.

    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
    });
    

    I hope this answer is helpful. We can use HTTP call instead static data.

    0 讨论(0)
  • 2020-12-12 18:19

    Perhaps you could try to use the of method of the Observable class:

    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());
      }
    }
    
    0 讨论(0)
  • 2020-12-12 18:24

    This way you can create Observable from data, in my case I need to maintain shopping cart:

    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;
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-12 18:28

    As of July 2018 and the release of RxJS 6, the new way to get an Observable from a value is to import the of operator like so:

    import { of } from 'rxjs';
    

    and then create the observable from the value, like so:

    of(someValue);
    

    Note, that you used to have to do Observable.of(someValue) like in the currently accepted answer. There is a good article on the other RxJS 6 changes here.

    0 讨论(0)
  • 2020-12-12 18:35

    Things seem to have changed since 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());
      }
    }
    

    The .next() function will be called on your subscriber.

    0 讨论(0)
提交回复
热议问题