Not able to consume external webapi service from a

2019-09-06 14:41发布

问题:

My requirement is to create a angular2 component which would consume the external WebAPI service and generate a bubblechart based on the data received. I have created a Dataservice component which would make the http get request. the code for Dataservice is below

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

The code for creating the bubblechart component is below: I am facing issues while trying to fetch the data returned by the GetExtractorQueuesLatest() method.

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

}

the Problem I am facing is the external webapi service method is not being called. I am not sure what is the mistake I have done here in the code, can any one please guide me on this and correct the mistakes?

回答1:

You're already subscribing in your GetExtractorQueuesLatest() method. You probably should rewrite it to just return an Observable and subscribe in the ngOnInit() of your component.

Also I think you should move the this.DrawBubbleChart() call into the subscribe lambda function, so it doesn't get called too early.

In your service:

public GetExtractorQueuesLatest() {

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

In your component:

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