簡體   English   中英

我怎樣才能在angularjs promise中解析這個結果

[英]how can I parse this result in angularjs promise

我有這樣的服務

app.service('newsService', function($q, $timeout,$http) {

  this.getNewsName = function(id) {
    var deferred = $q.defer();
    var newsId = parseInt(id, 10);

    $timeout(function() {

         $http({
                url: "entry/GetNewsTitle",
                 method: "POST",
                 data: $.param({'id':newsId}),
                 headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
                    })
                    .success(function(data, status, headers, config) {

                        deferred.resolve(data.name);
                    })
                    .error(function(data, status, headers, config) {
                        console.log('failed');
                    });
                }, 10);

    return deferred.promise;
  } 

另一個函數中的console.log(deferred.promise)給了我三個函數“catch”“finally”和“then”但是如何再次實現data.name呢?

像這樣:

newsService.getNewsName(id).then(function(name) {

});

首先,您應該優化服務方法以避免延遲反模式 您不需要創建虛擬延遲對象,因為$http(...)已經返回Promise。

該服務將如下所示:

app.service('newsService', function($http) {

    this.getNewsName = function(id) {
        return $http({
            url: "entry/GetNewsTitle",
            method: "POST",
            data: $.param({
                'id': parseInt(id, 10)
            }),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(data, status, headers, config) {
            return data.name;
        }).error(function(data, status, headers, config) {
            console.log('failed');
        });
    };

});

注意, getNewsName返回$http結果。

使用此服務的控制器將使用Promise API鏈接到它:

newsService.getNewsName(123).then(function(name) {
    console.log(name);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM