How to remove the json from the subscribe to pass it to an object?

0

I have a problem.

It happens that I have a json data that I receive from the database, and when entering the service that the json brings me I enter the subscribe and assign the data json to a variable. but the problem is that using the variable a to which the json assigned in this case of llama this.datos, if it leaves the subscribe is already empty, but within it is with the json that you assign.

I would like to know how I do this this data contains the json that I assign in the subscribe to use in other functions or operations.

This is the service call the json brings:

getDatos(){ 
    this._service.getDatos.subscribe(
        result => {             
            if(result.code = 200){
                 this.datos = result.data;
                 console.log(this.datos);
            }else{
                console.log(result);
            }

        },
        error => {
            console.log(<any>error);
        }
    );
}

This is the get service:

get getDatos(){
    return this._http.get(this.url+'*').map(res => res.json());
}

What I want is to use this data with the json assigned to it.

The variable this.data is declared at the beginning of the component.

Thanks

    
asked by DaVid Roa 27.09.2017 в 18:37
source

1 answer

1

The varibale this.datos will have data after the call to the server ends, if you try to access the varibale before the call to the server this will not have values since the call has not been completed or has not been made.

Note that the subscribe part is an asynchronous operation, therefore the subscribe part will be executed once the operation is finished. Then if you can work with the data that the server has returned.

// you can do something like that.

getDatos(){ 
    this._service.getDatos.subscribe(
        result => utilizarDatos(result),
        error => console.log(<any>error)
    );
}

private function utilizarDatos(result){
    this.datos = result;
    this.datos.forEach((item) => console.log(item));
}
    
answered by 27.09.2017 / 20:11
source