从角度2服务

时间:2016-02-10 08:12:45

标签: angularjs http

我的服务有以下代码

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的组件中。基本上,在这项服务中,我试图使用网址http://private-server.eviry.com/get_private_servers

获取私人服务器列表

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

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您还可以使用Event Emitter对响应进行异步响应。 以下是Angular2中Observables的一个很好的介绍。

答案 2 :(得分:0)

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