我有一个Angular 2项目,其中一个方法订阅了一个observable。 observable从服务器获取对象的排序列表,并将其返回以供在页面上查看。但是,由于某种原因,阵列正在失去它的顺序。
以下是将请求发送到服务器的服务的代码段:
template.service.ts
export class TemplateService {
constructor(private http: Http) { }
getTemplates(): Observable<any> {
let url = `controller/GetTemplateList`
return this.http.get(url)
.map(this.extractData)
.catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
}
这是订阅observable的组件:
templates.component.ts
export class TemplatesComponent implements OnInit {
constructor(private templateService: TemplateService) { }
ngOnInit() {
this.templateService.getTemplates().subscribe(res => {
console.log(res)
}, err => {
console.error(err);
});
}
}
服务器正在返回:
{"success":true,"list":["A","B","C","D","E","F","G","H","I","J","K","L"]}
但是当我在订阅上执行console.log时,它看起来像这样:
list:(12) ["G", "A", "C", "D", "E", "F", "B", "H", "I", "J", "K", "L"]
success:true
当我尝试使用3个元素的数组时,它可以正常工作,但是使用完整列表时它会无序返回。为什么它会在订阅上扰乱数组的顺序?
另外,如果我从getTemplates()方法中删除这两行,那么它看起来像这样:
getTemplates(): Observable<any> {
let url = `controller/GetTemplateList`
return this.http.get(url);
}
它返回正确的顺序如下:
_body:
"{"success":true,
"list: ["A","B","C","D","E","F","G","H","I","J","K","L"]}"