Search code examples
angularangular2-templateangular2-services

How to get response of a service in an array for use, in angular 2


I had declare an array.at .ts file:

responsearray:any=[];

Inside constructor:

constructor(private _dataService: UserService, private _ngZone: NgZone) {
 this.responsearray = this.getmarkers(id);
 this.moveMarker(this.responsearray);
}

I want to pass updated value of response array in movemarker function and it also updated inside function getmarkers, but updated values not reflected above:

getmarkers(id) {

this._dataService
    .GetMarker(id)
    .subscribe(res => {
            this.responseformate = Object.assign({}, res);
            this.responsearray = this.responseformate.responsepacket;

        },
        error => console.log(error),
        () => {
            return (this.responsearray);
        })
 }

Solution

  • Issue :

    You are returning value from async call , if you want to do it that way then you have to return observables and then have to subscribe the event , by simply returning value you will not get the expected result it will return the observable.

    Simple way to achieve output is :

    constructor(private _dataService: UserService, private _ngZone: NgZone) {
     this.getmarkers(id);
    }
    
    getmarkers(id) {
        this._dataService
        .GetMarker(id)
        .subscribe(res => {
                this.responseformate = Object.assign({}, res);
                this.responsearray = this.responseformate.responsepacket;
                this.moveMarker(this.responsearray);
            },
            error => console.log(error));
    }
    

    Another way :

    constructor(private _dataService: UserService, private _ngZone: NgZone) {
        this.getmarkers(id).subscribe(() => { 
            this.moveMarker(this.responsearray);
        });
    }
    
    getmarkers(id):Observable {
        return this._dataService
        .GetMarker(id)
        .map(res => {
                this.responseformate = Object.assign({}, res);
                this.responsearray = this.responseformate.responsepacket;
            },
            error => console.log(error));
    }