Pregunta

I'm relatively new to Angular and trying to correct some functionality someone left us with. I have a service that retrieves JSON from another service, and then I'd like to use that JSON within the original service. I have it working when accessing a single value from the JSON being returned, but I'd like to store the entire object so I can easily reference it throughout.

For instance, this works, and sets the value of title (title: cfgTitle) to the TITLE value coming back from the JSON:

.service("rtmModel", function($q, dataGetter, $http) {
    this.getModel = function() {
        var cfgProm = dataGetter.getData()
        var cfgTitle = cfgProm.then(function(response) {
            return response.data.record1.TITLE;
        });
        return {
            title: cfgTitle,
            desc: 
            ...

However, if I return anything else from the "then" function I can't get stuff to show up. For instance, this does not work (appears to be passing undefined for the title param):

.service("rtmModel", function($q, dataGetter, $http) {
    this.getModel = function() {
        var cfgProm = dataGetter.getData()
        var cfgTitle = cfgProm.then(function(response) {
            return response.data.record1;
        });
        return {
            title: cfgTitle.TITLE,
            desc: 
            ...

If I simply return "response" from the "then" function and do:

         return {
        title: cfgTitle.

then I get the entire JSON string passed into Title (and I understand why), but attempting to drill down (i.e. title: cfgTitle.data, or title: cfgTitle.data.record1) just results in undefined values.

I've tried various methods of storing the returning JSON data, but can't find the secret sauce that will allow me to store the JSON object, and then use it to pass multiple parameters down below (i.e. I want to pass a value into title, another into desc, and so forth).

Any pointers would be appreciated.

¿Fue útil?

Solución

You can't return values/objects from the anonymous function callbacks that you pass to the .then method of a promise. Those callbacks are invoked internally by the promise library and the return value is ignored. You have two options. Refer a reference to a new object from getModel and copy the data returns from getData into it. Or, return a new promise from your getModel method, and resolve that promise when the promise returned from getData is resolved.

The later option (returning a promise to the caller) will look something like this (won't compile):

.service("rtmModel", function($q, dataGetter, $http) {
this.getModel = function() {
    var defer = $q.defer();
    dataGetter.getData().then(function(response) {
        defer.resolve(response.data.record1);
    });
    return defer.promise;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top