繁体   English   中英

Angular 2服务未从HTTP响应返回JSON

[英]Angular 2 Service Not Returning JSON from HTTP Response

我正在尝试从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);
  }

}

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

将我的代码更改为以下代码,这意味着该服务现在可以从该服务调用中获取任何URL,而不是从该服务内部获取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));
}

1. const headers = new Headers({'Content-Type':'application / json','Cache-control':'no-cache',Expires:'0',Pragma:'no-cache'});

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

您必须将这个“选项”与url一起发送。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM