Home > OS >  Angular 2 > How to wait several Observable into Observable
Angular 2 > How to wait several Observable into Observable

Time:08-03

I try to get IP (public and private) from user (this 2 functions works well) before sending post request. Here is my problem, I don't achieve to wait before get datas to do the post request...

Here is my 2 Observables:

this.ip_wan$ = new Observable(observer => {
  this.http.get("https://api.ipify.org/?format=json").subscribe((response: any) => {
    this.ip_wan = response.ip;
    observer.complete();
  });
});

this.ip_lan$ = new Observable(observer => {
  if (window.RTCPeerConnection) {
    let ip = [];
    var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
    pc.createDataChannel('');
    pc.createOffer(pc.setLocalDescription.bind(pc), noop);
    pc.onicecandidate = function(event) {
      if (event && event.candidate && event.candidate.candidate) {
        var s = event.candidate.candidate.split('\n');
        s.forEach(ip => {
          this.ip_lan.push(ip.split(' ')[4])
        });
        observer.complete();
      }
    }.bind(this)
  }
});

And my another observable called by another modules to do the post request:

getUserByToken(token): Observable<UserModel> {
const httpHeaders = new HttpHeaders({
  Authorization: `Bearer ${token}`,
});

return this.ip_wan$.pipe(
  mergeMap(() => {
    return this.ip_lan$.pipe(
        concatMap(() => {
          return this.http.post<UserModel>(API_URL, JSON.stringify({ ip_wan: this.ip_wan, ip_lan: JSON.stringify(this.ip_lan) }), { headers: httpHeaders });
        }),
        take(1),
    )
  }),
  take(1),
).subscribe();

}

I got this error: "this.authHttpService.getUserByToken(...).pipe is not a function". I try lots of things but nothing seems to work. I need help because I think I misunderstood observable...

CodePudding user response:

Remove the subscribe() at the end, your are returning a subscription instead of an observable in the getUserByToken function. The error is correct as the Subscription object doesn't have any .pipe function defined.

CodePudding user response:

I think the problem is with your ip_wan$, you don't need to create an observable from something that already is an observable, http already gives you one, the other thing is that you shouldn't subscribe to an observable if later on, you need to unwrap it, for that, just pipe it if necessary, try the following:

// you don't subscribe here
this.ip_wan$ = this.http.get("https://api.ipify.org/?format=json").pipe(
tap((response: any) => this.ip_wan = response.ip)
);
  • Related