无法将对象从角度服务传递给控制器

时间:2017-02-02 20:41:26

标签: javascript angularjs typescript

我使用$ http.get我的对象服务,然后将其传递给我的控制器。

当我加载网页并使用F12开发人员工具时 - 自定义服务(getService)正常工作以获取数据对象并将其存储在responseObj.Announcement变量中。我可以使用Chrome查看范围并查看我的对象。 我无法将该对象传递给我的控制器

  • 我的某个方法在服务或控制器中是否存在问题?

我已经在stackOverflow上下寻找类似的情况但是我很难过。

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

1 个答案:

答案 0 :(得分: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