2017-03-22 47 views
0

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

这是我的组件:

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 
} 

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

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

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

谢谢!

回答

1

您可以链接observable,当您的this.ipSrv.getIp()您的下一个运营商将收到Ip对象。在你的组件在下一个操作符是subscribe(),但您可以使用,例如,switchMap()和数据传递到其他服务:

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