Search code examples
angularobservable

Angular 2+ > How to wait several Observable into Observable


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...


Solution

  • 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.