Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - How to create an http observable that makes dynamic requests

I have an observable that makes dynamic requests.

For example,

getFlowers(params?: any): Obeservable<Flower[]> {
  return this.http.get<Flower[]>(
    `http://flowers.com/flowers`, { params }
  )
}

Now, the above function returns new http observable each function call. I would like to somehow achieve returning the same observable instance (despite making different http calls) such that I can use switchMap to cancel previous simultaneous requests.

I have an idea that I should create an Observable property (singleton), but I fail to realize how to utilize it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now, the above function returns new http observable each function call??

This is actually the normal behavior of the HTTP observables as they are Cold. When a cold observable has multiple subscribers, the whole data stream is re-emitted for each subscriber. Each subscriber becomes independent and gets its own stream of data
Approach:1
To Avoid Duplication of HTTP Requests you can use shareReplay operator.

import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { shareReplay, tap } from "rxjs/operators";
@Injectable()
export class ShareService {
  public response$: Observable<any>;
  constructor(private httpc: HttpClient) {
    this.sendRequest();
  }
  public sendRequest() {
    this.response$ = this.httpc.get("url").pipe(
      tap(res => {
        console.log("called");
        return res;
      }),
      shareReplay(1)
    );
  }
  fetchData() {
    return this.response$;
  }
}

component1:

constructor(service: ShareService) {
    service.fetchData().subscribe(result => {
      console.log(result);
    });
  }

component2:

   constructor(service: ShareService) {
    service.fetchData().subscribe(result => {
      console.log(result);
    });
  }

Further Reading

Live Demo
Approach:2
If your objective is to multicast the data use RXJS's Subject or BehaviorSubject
Subject acts as a bridge/proxy between the source Observable and many observers, making it possible for multiple observers to share the same Observable execution.
This recommended way of exposing Subjects are using the asObservable() operator.

@Injectable()
export class MyProvider {
  private myObservable=new Subject<any>();
  CurrentData = this.myObservable.asObservable();
  constructor(private aFs: AngularFirestore) {
    //your logic
      this.myObservable.next(value);//push data into observable
  }


}

Page.ts

this.mySubscription = this.myProvider.CurrentData.subscribe(value => {
      //something that works
    });

Using Behavior Subject

@Injectable()
export class MyProvider {
  private myObservable = new BehaviorSubject<any>("");
  CurrentData = this.myObservable.asObservable();
  constructor(private aFs: AngularFirestore) {}

  getData(myParam): void {
    someasynccall
      .pipe(
        map(),
        filter()
      )
      .subscribe(value => this.myObservable.next(value));
  }
}

Page.ts

this.myProvider.getData(param);
this.mySubscription = this.myProvider.CurrentData.subscribe(value => {
      //something that works
    });

Subject vs BehaviorSubject

LiveDemo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...