angularjs函数返回的数组是一个对象,而不是一个字符串

时间:2017-11-06 04:06:56

标签: javascript angularjs

我遇到一些问题,让下面的函数作为可用的字符串返回?

我的代码是:

app.factory('Urls', ['$http', function($http) {
    var urls = {};
    urls.getUrls = function () {
        return  $http.get('json/dataUrls.json'); 
    }
    return urls
}]);

app.factory('Emails', ['$http', 'Urls', function($http, Urls) {

    var dataUrl = Urls.getUrls().then(function(response) {
        return response.data.emails;
    });
    console.log(dataUrl);

    var query = {};
    query.getItems = function() {
        return  $http.get('json/emails.json');  
    };
    return query;
}]);

下面是console.log(dataUrl);的结果我想要的是值字符串......

f {$$state: {…}}
$$state
:
status
:
1
value
:
"json/emails.json"
__proto__
:
Object
__proto__
:
Object

3 个答案:

答案 0 :(得分:2)

Urls.getUrls().then(...)返回一个promise(read more about this here),一个用于保存"引用的数据类型"到异步获取的值。因此,在console.log上运行dataUrl将返回一个对象,而不是字符串。

要获取此值,您需要异步访问它。最好的方法是通过promise chaining

app.factory('Urls', ['$http', function($http) {
    var urls = {};
    urls.getUrls = function () {
        return  $http.get('json/dataUrls.json'); 
    }
    return urls
}]);

app.factory('Emails', ['$http', 'Urls', function($http, Urls) {

    Urls.getUrls().then(function(response) {
        return response.data.emails;
    }).then(function(emails){
        console.log(emails);
    });

    var query = {};
    query.getItems = function() {
        return  $http.get('json/emails.json');  
    };
    return query;
}]);

答案 1 :(得分:1)

你从var dataUrl = Urls.getUrls().then(...得到的DataUrls实际上是一个Promise,而不是一个String。我想你的意图就像是吼叫:

app.factory('Urls', ['$http', function($http) {
    var urls = {};
    urls.getUrls = function () {
        return  $http.get('json/dataUrls.json'); 
    }
    return urls
}]);

app.factory('Emails', ['$http', 'Urls', function($http, Urls) {

    var query = {};
    query.getItems = function() {
        return Urls.getUrls().then(function(response) {
            return response.data.emails;
        }).then(dataUrls => { // dataUrls here is a string, you can use it.
            return  $http.get(dataUrls); 
        });
    };
    return query;
}]);

答案 2 :(得分:0)

app.factory('Urls', ['$http', function($http) {
    var urls = {};
    urls.getUrls = function () {
        return  $http.get('json/dataUrls.json'); 
    }
    return urls
}]);

app.factory('Emails', ['$http', 'Urls', function($http, Urls) {

    Urls.getUrls().then(function(response) {
        return response.data.emails;
    }).then(function(emails){
        console.log(emails);
    });

    var query = {};
    query.getItems = function() {
        return  $http.get('json/emails.json');  
    };
    return query;
}]);