繁体   English   中英

从angular 2服务返回http响应

[英]Returning http response from a angular 2 service

我的服务有以下代码

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {Response} from "angular2/http";
import {PRIVATE_SERVERS} from "../mock/private_servers_list";
import 'rxjs/Rx';
/*import {PRIVATE_SERVERS} from "../mock/private_servers_list";*/

@Injectable()
export class PrivateServerService {
    http= null;
    PRIVATE_SERVERS = null;

    constructor(http:Http){
        this.http = http;
    }

    logError(err){
        console.log("some error");
    }

    getPrivateServers(){
        this.http.get('http://private-server.eviry.com/get_private_servers')
            .map(res => res.json())
            .subscribe(
                data => this.PRIVATE_SERVERS = data, //printing data here gives me the correct value
                err => this.logError(err),
                () => console.log('Private Server fetching complete')
            );

        console.log(this.PRIVATE_SERVERS);
        return this.PRIVATE_SERVERS;

    }
}

我已将此服务注入到名为private-server.component的组件中。 基本上,在此服务中,我尝试使用URL http://private-server.eviry.com/get_private_servers获取私有服务器列表。

我在getPrivateServers()函数中访问此URL。 当我在subscription方法中打印响应时,我可以看到正确提取的数据。

但是,当我尝试console.log(this.PRIVATE_SERVERS) ,它显示null。 这是使用角度服务的正确方法还是有办法让它等待响应?

分配发生在异步回调中。 如果要在回调之外使用它的值,则需要等待它完成。

您还可以使用事件发射器对响应进行异步响应。 这是Angular2中Observables的很好的介绍。

PrivateServerService.ts

import { Injectable } from 'angular2/core';
import { Http } from 'angular2/http';
import { Response } from "angular2/http";
import { PRIVATE_SERVERS } from "../mock/private_servers_list";
import 'rxjs/Rx';
/*import {PRIVATE_SERVERS} from "../mock/private_servers_list";*/

@Injectable()
export class PrivateServerService {
    PRIVATE_SERVERS = null;

    constructor(private http: Http) {
        this.setPrivateServerMocksData();
    }

    logError(err) {
        console.log("some error");
    }

    getPrivateServers() {
        return this.http.get('http://private-server.eviry.com/get_private_servers')
            .map(res => res.json());
    }

    setPrivateServerMocksData() {
        this.getPrivateServers()
            .subscribe((data) => {
                this.PRIVATE_SERVERS = data
                console.log(this.PRIVATE_SERVERS);
            },
            (err) => {
                this.logError(err)
            });
    }

}

YourComponent.ts

 getPrivateServerInfo() {
                this.privateServerService.getPrivateServers()
                    .subscribe((data) => {
                        //you have your data here to work with
                        console.log(data);
                    },
                    (err) => {
                        this.logError(err)
                    });
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM