2017-12-26 3 views
1

Service in Controller에서 데이터에 액세스하는 데 문제가 있습니다. Here`s 내 서비스의 파일 코드 :TypeScript에서 각도 1.6을 사용하는 서비스에서 데이터를 가져올 수 없습니다.

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`s 파일 코드 :

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

} 

는 사람이 내 코드를 잘못 what`s 설명 할 수 있습니까? 감사.

답변

0

함수 선언을 아래의 방법으로 변경하거나 (컨텍스트)이 보존되도록 Arrow 함수를 사용하십시오. 또한 getItems 메서드에서 $http 약속을 반환해야합니다. 그렇지 않으면 .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; 
    }); 
} 
+1

하하! 당신은 빨리 형편이되었습니다. – Sajeetharan

+0

형제 님, 고마워요.하지만 여전히 작동하지 않습니다. (( –

+0

Downvoter, 왜 하향 투표를 하시겠습니까?) 감사합니다. –

0

getItems 방법 내부의 약속, 그것은해야합니다 반환,

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

형님, 고마워요. 작업(( –

관련 문제