Angular 2服务不从HTTP响应中返回JSON

时间:2018-01-30 22:52:14

标签: json angular2-services

我正在尝试从web api返回JSON数据,该服务收集这个很好,当你将它输出到控制台时它工作并返回我期望的,但当我尝试将数据返回到服务之外的某个地方我只能在没有错误的情况下找回'undefined'。

服务方法

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

}

2 个答案:

答案 0 :(得分:0)

在这里找到了一篇关于更好的方法的好文章: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));
}

答案 1 :(得分:0)

1。  const headers = new Headers({       'Content-Type':'application / json',       '缓存控制':'无缓存',       过期:'0',       Pragma:'no-cache'     });

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

您必须将此“选项”与网址一起发送。

相关问题