Teleuko
Teleuko

Reputation: 31

Use observable service as parameter in angular 2

I'm developing an app based on IP client detection. The idea is get the IP of the client through the ipify API and then search for the IP in my database through a client API. How can I use the result of the ipify API to pass it as parameter to a new Service?

This is my Component:

import { Component, OnInit } from '@angular/core';
import { IpService } from './ip.service';
import { NodeService } from './node.service';

export interface Ip {
  ip: string,
}

@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app works!';

  ipObj: Ip[] = [];
  errorMessage: string;

  constructor(private ipSrv: IpService) { }

  ngOnInit() {
    this.getIp();
  }

  getIp() {
    return this.ipSrv.getIp()
      .subscribe(
      res => { this.ipObj = res; console.log(this.ipObj) },
      error => this.errorMessage = <any>error);
  }
}

This is the Service:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

export interface Ip{
  ip: string;
}

@Injectable()
export class IpService {

  private ipifyUrl = '//api.ipify.org/?format=json';
  private apiUrl = '//localhost:3000/api/ip/';

  constructor(private http: Http) { }

  getIp(): Observable<Ip[]> {
    return this.http.get(this.ipifyUrl)
      .map(res => res.json())
  }

}

When I use in my template view {{ipObj.ip}} it works. API responses:

{
ip: 209.69.65.9
}

How can I use the result in my Component and pass it as parameter to a new function? I need something like this:

this.nodeService.getIp("209.69.65.9").map(res => this.node = res);

So, search for an institution with this IP.

Thanks in avance!

Upvotes: 0

Views: 610

Answers (1)

Sasxa
Sasxa

Reputation: 41254

You can chain observables, when you this.ipSrv.getIp() your next operator will receive Ip object. In your component this next operator is subscribe(), but you can use, for example, switchMap() and pass data to your other service:

return this.ipSrv.getIp()
  .switchMap(ipObj => this.nodeService.getIp(ipObj.ip))
  .map(res => this.node = res)
  .subscribe()

Upvotes: 2

Related Questions