簡體   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