Duplicated http request in ionic 2 with asynchronous tube

I am new to ionic 2. I am using ionic v3.6.1.

Please note that the HTTP request is fire x times, where x is the binding of the request to a message with an asynchronous channel. So, in this case, the http request is run 3 times.

Please advise, this is the best practice.

Provider:

  getPostById(id: number) {
    return this.http.get(`${this.rootUrl}/${this.posts}/${id}`).map(res => res.json()).take(1);
  }

ts file:

post: Observable<Post>;
ionViewDidLoad() {
    this.postId = this.navParams.get('postId');
    console.log(this.postId);
    this.post = this.data.getPostById(this.postId);
  }

HTML

{{ (post | async)?.id }}
{{ (post | async)?.title}}
{{ (post | async)?.content}}
+4
source share
2 answers

Operator share()

, Observable, . - . , .share() operator ( .publish().refCount(), . ):

, () Observable. , Observable . , Observable. Observable - , . .publish().refCount().

ionViewDidLoad() {
    this.postId = this.navParams.get('postId');
    console.log(this.postId);
    this.post = this.data.getPostById(this.postId).share();
  }

Observable , , (*ngIf), , , .

:

:

{{ (post | async)?.id }}
<div *ngIf="post|async">
    {{ (post | async)?.title}}
    {{ (post | async)?.content}}
</div>

ts:

post: Observable<Post>;
ionViewDidLoad() {
    setTimeout(()=>this.show=true, 5000);
    this.postId = this.navParams.get('postId');
    console.log(this.postId);
    this.post = this.data.getPostById(this.postId).share();
  }

share () , , ngIf , Observable, . - :

myPostID
<div></div>

:

  • .publishReplay(n): n - , Observable. refCount(), reset , .

    this.post = this.data.getPostById(this.postId).publishReplay(1).refCount();
    
  • *ngIf="post |async as myPost" angular 4 (, , 4.1, ), myPost. . , .share() ts- :

    {{ (post | async)?.id }}
    <div *ngIf="post|async as myPost">
        {{ myPost.title}}
        {{ myPost.content}}
    </div>
    

2 publish() refCount():

publish() Observable ConnectableObservable. Observable , connect() ( ).

:

Rx.Observable.prototype.publish([selector])

, , .

refCount() - , ConnectableObservable, connect() . , , .

:

ConnectableObservable.prototype.refCount()

, , .

+2

:

.ts

post: Post;
ionViewDidLoad() {
    this.postId = this.navParams.get('postId');
    console.log(this.postId);
    this.data.getPostById(this.postId).subscribe(data => {
        this.post= data;
    });

  }

:

.html

{{ post?.id }}
{{ post?.title}}
{{ post?.content}}
+1

Source: https://habr.com/ru/post/1685509/


All Articles