无法从 angular2 服务使用外部 webapi 服务 [英] Not able to consume external webapi service from angular2 service

查看:25
本文介绍了无法从 angular2 服务使用外部 webapi 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是创建一个 angular2 组件,该组件将使用外部 WebAPI 服务并根据收到的数据生成气泡图.我创建了一个 Dataservice 组件,它将发出 http get 请求.Dataservice的代码如下

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

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

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

}

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

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?

推荐答案

您已经订阅了 GetExtractorQueuesLatest() 方法.您可能应该将其重写为仅返回一个 Observable 并在您的组件的 ngOnInit() 中订阅.

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.

此外,我认为您应该将 this.DrawBubbleChart() 调用移动到 subscribe lambda 函数中,以免过早调用它.

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

在您的服务中:

public GetExtractorQueuesLatest() {

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

在您的组件中:

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

这篇关于无法从 angular2 服务使用外部 webapi 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆