【问题标题】:Can not get data from service using angular 1.6 with TypeScript无法使用带有 TypeScript 的 Angular 1.6 从服务中获取数据
【发布时间】:2018-06-07 04:52:54
【问题描述】:

我在从 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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      将函数声明更改为以下方式或使用Arrow 函数,以便保留类的this(context)。另外你必须从getItems方法返回$httppromise,否则你不能在它上面应用.then方法来链promise。

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

      【讨论】:

      • 投反对票的人你介意说,你为什么投反对票?谢谢
      猜你喜欢
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      相关资源
      最近更新 更多