简体   繁体   中英

Angular 2 Service Not Returning JSON from HTTP Response

I'm attempting to return JSON data from a web api, the service collects this fine and when you output this to the console it works and returns what I expect, but when I try to return the data to somewhere outside the service I can only get back 'undefined' with no errors.

Service Method

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

Service Call (in component)

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

}

Found a great article on much better way to do this here: https://hassantariqblog.wordpress.com/2016/12/03/angular2-http-simple-get-using-promises-in-angular-2-application/

Changed my code to the following, meaning the service can take any URL now from from the service call as opposed to inside the service:

Service Method(s):

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

Service Call:

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

You have to send this 'options' along with url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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