使用可观察服务作为角度2中的参数

时间:2017-03-22 20:37:14

标签: angular

我正在开发基于IP客户端检测的应用程序。想法是通过ipify API获取客户端的IP,然后通过客户端API在我的数据库中搜索IP。如何使用ipify API的结果将其作为参数传递给新服务?

这是我的组件:

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);
  }
}

这是服务:

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())
  }

}

当我在我的模板视图{{ipObj.ip}}中使用时,它可以工作。 API响应:

{
ip: 209.69.65.9
}

如何在Component中使用结果并将其作为参数传递给新函数?我需要这样的东西:

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

因此,搜索具有此IP的机构。

谢谢你!

1 个答案:

答案 0 :(得分:2)

this.ipSrv.getIp()您的下一位运营商将收到Ip个对象时,您可以链接可观察对象。在您的组件中,下一个运算符为subscribe(),但您可以使用switchMap(),并将数据传递到其他服务:

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