2017-02-02 13 views
0

私のオブジェクトを$ http.getにサービスを使用していて、それをコントローラに渡しています。角度サービスからコントローラにオブジェクトを渡すことができません

WebページをロードしてF12開発ツールを使用すると、カスタムサービス(getService)が正常に動作してデータオブジェクトを取得し、responseObj.Announcement変数に格納します。スコープを見て自分のオブジェクトを見るためにChromeを使うことができます。 私は、サービスまたはコントローラのいずれかで私のいずれかの方法で問題があり、私のコントローラ

  • にそのオブジェクトを渡すことができないんですか?

私は似たような状況を探していますが、私は困惑しています。

のgetServiceは



    class getService { 
     static $inject = ["$http", "$window"] 
     baseUrl: string = ConfigB.BaseAPIUrl; 


     urlObject = { 
      Announcement: "Announcement", 
     }; 

     responseObj = { 
      Announcement :[], 

     }; 

     constructor(
      public $http: any, 
      private $window: any 
     ) { } 



     // method utilizing generic promise object for announcements controller 
     public getAnnouncements() 
     { 
      this.getRequest(this.baseUrl + this.urlObject.Announcement, "Announcement"); 

     } 

     public passData() 
     { 
      return this.responseObj.Announcement; 
     } 


     //Generic angular $http promise object 
     private getRequest(url: string, responseType:string) 
     { 


      this.$http.get(url) 
       .then((response) => 
       { 
        this.responseObj[responseType] = response.data; 

       }, 
       function (data) { 
        this.$window.alert("Error: " + data); 
       }); 
     } 
    } 
    angular.module('App').service("getService", getService); 

**My Controller:** 

<pre><code> 

class announcementController { 
    static $inject = ["$rootScope", "$scope", "$window", "getService" ]; 

    Announcement: any = [ 
     { Message: "test" } 
    ]; 
    constructor(
     public $rootScope: any, 
     public $scope: any, 
     private $window: any, 
     private getService: any) 
    { 

    } 

    public getAnnouncements() { 

     this.getService.getAnnouncements() 


    } 

    public setAnnouncements() { 
     this.Announcement = this.getService.passData(); 
    } 

    init() { 
     this.getAnnouncements(); 
     this.setAnnouncements(); 
    }  
} 
angular.module('App').controller("announcementController", announcementController); 

+0

あなたがのgetServiceを実行する前に終了する()のGetRequestを待っているようには見えません。 passData()。 –

答えて

1

あなたはsetAnnouncements()を実行する前に解決することを約束$ HTTPを待つ必要があります。これは、$ httpが返す約束を渡し、コントローラが終了したらデータを取得することで実現できます。あなたのサービスで

public getAnnouncements() 
{ 
    return this.getRequest(this.baseUrl + this.urlObject.Announcement, "Announcement"); 
} 

private getRequest(url: string, responseType:string) 
{ 
    return this.$http.get(url) 
    ... 

コントローラで:

public getAnnouncements() { 
    return this.getService.getAnnouncements(); 
} 

init() { 
    this.getAnnouncements().then(() => { 
     this.setAnnouncements(); 
    }); 
} 

Example JSBin

+0

Jamesさんは私の問題を解決し、約束をもっと教えてくれました。どうもありがとうございます! – Jake

関連する問題