【问题标题】:Angular 2 Service Not Returning JSON from HTTP ResponseAngular 2 服务未从 HTTP 响应返回 JSON
【发布时间】:2018-01-30 22:52:14
【问题描述】:

我正在尝试从 Web api 返回 JSON 数据,该服务很好地收集了这个数据,当你将它输出到控制台时它可以工作并返回我所期望的,但是当我尝试将数据返回到服务之外的某个地方时我只能返回“未定义”而没有错误。

服务方式

// Dashboard API Services 
  getModules() {
    this._http.request(this._baseUrl + "Modules/Get").subscribe((res: Response) => {
      this.modules = res.json();
    });
    return this.modules;
  }

服务调用(在组件中)

import { Component, OnInit } from '@angular/core';
import { KoapiService } from '../koapi.service';
import { Http } from "@angular/http";

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  modules: any;

  constructor(private _koapi: KoapiService) { }

  ngOnInit() {
    this.modules = this._koapi.getModules();
    console.log(this.modules);
  }

}

【问题讨论】:

    标签: json angular2-services


    【解决方案1】:

    在这里找到了一篇关于更好的方法的好文章:https://hassantariqblog.wordpress.com/2016/12/03/angular2-http-simple-get-using-promises-in-angular-2-application/

    将我的代码更改为以下内容,这意味着服务现在可以从服务调用中获取任何 URL,而不是在服务内部:

    服务方法:

      // On successful API call
      private extractData(res: Response) {
        let body = res.json();
        return body || {};
      }
    
      // On Erronious API Call
      private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
      }
    
      // Basic Get
      getService(url: string): Promise<any> {
        return this._http
            .get(this._baseUrl + url)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
      }
    

    服务电话:

    // Get Enabled Modules 
    this._koapi
      .getService("Modules/Get")
      .then((result) => {
        this.modules = result; 
        console.log(this.modules);
      })
      .catch(error => console.log(error));
    }
    

    【讨论】:

      【解决方案2】:

      1。 常量标头 = 新标头({ '内容类型':'应用程序/json', '缓存控制':'无缓存', 过期:'0', Pragma: '无缓存' });

      const options = new RequestOptions({ headers: headers });

      您必须将此“选项”连同 url 一起发送。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多