简体   繁体   English

从angular 2服务返回http响应

[英]Returning http response from a angular 2 service

I have the following code for my 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;

    }
}

I have injected this service in to a component called private-server.component. 我已将此服务注入到名为private-server.component的组件中。 Basically, in this service I am trying to get a list of private servers using the url http://private-server.eviry.com/get_private_servers 基本上,在此服务中,我尝试使用URL http://private-server.eviry.com/get_private_servers获取私有服务器列表。

I access this url in getPrivateServers() function. 我在getPrivateServers()函数中访问此URL。 When I print the response within the subscribe method, I can see the data fetched correctly. 当我在subscription方法中打印响应时,我可以看到正确提取的数据。

However, when I try to console.log(this.PRIVATE_SERVERS) , it prints null. 但是,当我尝试console.log(this.PRIVATE_SERVERS) ,它显示null。 Is this the correct way to use the angular service or is there a way to make it wait for the response? 这是使用角度服务的正确方法还是有办法让它等待响应?

The assignment happens in an asynchronous callback. 分配发生在异步回调中。 If you want to use its value outside that callback, you need to wait for it to complete. 如果要在回调之外使用它的值,则需要等待它完成。

You can also use Event Emitter to react asynchronous to the response. 您还可以使用事件发射器对响应进行异步响应。 Here is an good introduction to Observables in Angular2. 这是Angular2中Observables的很好的介绍。

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