简体   繁体   中英

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

I access this url in getPrivateServers() function. When I print the response within the subscribe method, I can see the data fetched correctly.

However, when I try to console.log(this.PRIVATE_SERVERS) , it prints 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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