首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从angular2服务使用外部webapi服务

无法从angular2服务使用外部webapi服务
EN

Stack Overflow用户
提问于 2016-06-10 05:12:50
回答 1查看 385关注 0票数 0

我的需求是创建一个angular2组件,该组件将使用外部WebAPI服务,并根据接收到的数据生成泡泡图。我已经创建了一个数据服务组件,它将发出http get请求。数据服务的代码如下所示

代码语言:javascript
复制
import { Injectable } from 'angular2/core';
import { HTTP_PROVIDERS, Http, Headers, Response, JSONP_PROVIDERS, Jsonp } from 'angular2/http';
import { Configuration } from './Configuration';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';

///Service class to call REST API
@Injectable()
export class DataService {

    private DataServerActionUrl: string;
    private headers: Headers;
    result: Object;

    constructor(private _http: Http, private _configuration: Configuration) {
        this.DataServerActionUrl = "http://localhost:23647/api/extractorqueue/getextractorqueueslatest/"; 

        this.headers = new Headers();
        this.headers.append('content-type', 'application/json');
        this.headers.append('accept', 'application/json');
    }

    public GetExtractorQueuesLatest() {

       return this._http.get(this.DataServerActionUrl)
            .map(response => response.json())
            .subscribe((res) => {
                this.result = res;
                console.log(this.result);
            },
            (err) => console.log(err),
            () => console.log("Done")
            );
    }

创建冒泡图组件的代码如下:我在尝试获取GetExtractorQueuesLatest()方法返回的数据时遇到了问题。

代码语言:javascript
复制
import { HTTP_PROVIDERS, Http, Headers, Response, JSONP_PROVIDERS, Jsonp } from 'angular2/http';
import { Component, OnInit } from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import { DataService } from '../DataService';
declare var d3: any;

@Component({
    //selector: 'bubble-chart',

    styles: [``],
    directives: [CORE_DIRECTIVES],
    providers: [DataService],
    //template: ``
    templateUrl:'bubblechart.html'
})

export class BubbleChartComponent implements OnInit {
    public resultData: any;
    _http: Http;
    private headers: Headers;
   constructor(private _dataService: DataService) { }

   ngOnInit() {
       this._dataService
           .GetExtractorQueuesLatest().subscribe(res => this.resultData = res);
            error => console.log(error),
            () => console.log('Extractor Queues Latest'));

        this.DrawBubbleChart();
    }

    margin = 25;
    diameter = 915;
    color = d3.scale.linear()
        .domain([-1, 5])
        .range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"])
        .interpolate(d3.interpolateHcl);

    pack = d3.layout.pack()
        .padding(2)
        .size([this.diameter - this.margin, this.diameter - this.margin])
        .value(function (d) { return d.size; })

    svg = d3.select("router-outlet").append("svg")
        .attr("width", this.diameter)
        .attr("height", this.diameter)
        .append("g")
        .attr("transform", "translate(" + this.diameter / 2 + "," + this.diameter / 2 + ")");

    private DrawBubbleChart(): void {

        var chart = d3.json(this.resultData, (error, root) => {
            if (error) throw error;

            var focus = root,
                nodes = this.pack.nodes(root),
                view;

            var circle = this.svg.selectAll("circle")
                .data(nodes)
                .enter().append("circle")
                .attr("class", function (d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
                .style("fill", (d) => { return d.children ? this.color(d.depth) : null; })
                .on("click", (d) => { if (focus !== d) zoom.call(this, d), d3.event.stopPropagation(); });

            var text = this.svg.selectAll("text")
                .data(nodes)
                .enter().append("text")
                .attr("class", "label")
                .style("fill-opacity", function (d) { return d.parent === root ? 1 : 0; })
                .style("display", function (d) { return d.parent === root ? "inline" : "none"; })
                .text(function (d) { return d.name; });

            var node = this.svg.selectAll("circle,text");

            d3.select("router-outlet")
                .style("background", this.color(-1))
                .on("click", () => { zoom.call(this, root); });

            zoomTo.call(this, [root.x, root.y, root.r * 2 + this.margin]);

            function zoom(d) {
                var focus0 = focus; focus = d;

                var transition = d3.transition()
                    .duration(d3.event.altKey ? 7500 : 750)
                    .tween("zoom", (d) => {
                        var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + this.margin]);
                        return (t) => { zoomTo.call(this, i(t)); };
                    });

                transition.selectAll("text")
                    .filter(function (d) { return d.parent === focus || this.style.display === "inline"; })
                    .style("fill-opacity", function (d) { return d.parent === focus ? 1 : 0; })
                    .each("start", function (d) { if (d.parent === focus) this.style.display = "inline"; })
                    .each("end", function (d) { if (d.parent !== focus) this.style.display = "none"; });
            }

            function zoomTo(v) {
                var k = this.diameter / v[2]; view = v;
                node.attr("transform", function (d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; });
                circle.attr("r", function (d) { return d.r * k; });
            }
        });
    }

}

我面临的问题是外部webapi服务方法没有被调用。我不确定我在代码中做的错误是什么,有人可以在这方面指导我并纠正错误吗?

EN

回答 1

Stack Overflow用户

发布于 2016-06-10 15:08:50

您可能应该重写它,使其只返回一个Observable并在组件的ngOnInit()中订阅。

另外,我认为您应该将this.DrawBubbleChart()调用移到subscribe的lambda函数中,这样它就不会被过早地调用。

服务中的

代码语言:javascript
复制
public GetExtractorQueuesLatest() {

   return this._http.get(this.DataServerActionUrl)
        .map(response => response.json());
}

组件中的

代码语言:javascript
复制
ngOnInit() {
    this._dataService.GetExtractorQueuesLatest()
        .subscribe(
            (res) => {
                this.resultData = res;
                this.DrawBubbleChart();
            },
            (error) => console.log(error),
            () => console.log('Extractor Queues Latest')
        );
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37736268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档