使用TypeScript使用angular 1.6无法从服务获取数据

问题描述 投票:1回答:2

我在从Controller中的服务访问数据时遇到问题。这是我服务的文件代码:

import {IHttpService} from 'Angular';

export class MyService {
public static $inject = ['$http'];
constructor(private $http:IHttpService, private getItems){

this.getItems= function() {
  this.$http.get('items.json').then(function(response){
    if(err){
      console.error(err);
    }
    console.log(response.data);
    return response.data;
  });
}}}

和Controller的文件代码:

import {MyService} from './MyService';
export class MyController {
public:getData;
static inject: Array<string> = ['$http', '$scope', 'MyService'];
constructor(private $http:ng.IHttpService, private $scope:any, private MyService:any){
    this.getData = function(){
      MyService.getItems.then(function (data) {
      this.getItems = data;

      console.log(data);
    });
  }

}

任何人都可以解释我的代码有什么问题吗?谢谢。

angularjs typescript angularjs-http
2个回答
0
投票

在getItems方法中返回promise,它应该是,

this.getItems= function() {
  return this.$http.get('items.json').then(function(response){
    if(err){
      console.error(err);
    }
    console.log(response.data);
    return response.data;
  });
}}}

0
投票

将函数声明更改为以下方式或使用Arrow函数,以便保留类的this(上下文)。此外,您必须从$http方法返回getItems承诺,否则您不能将.then方法应用于链承诺。

getItems() {
  //return promise here.
  return this.$http.get('items.json').then((response) => {
    if(err){
      console.error(err);
    }
    console.log(response.data);
    //returning data to chained promise.
    return response.data;
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.