angular 2 中如何获取数组中服务的响应以供使用

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

我已经声明了一个 array.at .ts 文件:

responsearray:any=[];

内部构造函数:

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

我想在 movemarker 函数中传递响应数组的更新值,它也在函数 getmarkers 中更新,但更新值没有反映在上面:

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);
        })
 }

问题:

你正在 return 从异步调用中获取值,如果你想那样做,那么你必须 return observables 然后必须订阅事件,只需 returning 值你不会得到预期的结果它会 return 可观察到的。

实现输出的简单方法是:

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));
}

另一种方式:

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));
}