我使用ng2-select来显示项目列表,以便用户可以从选择列表中搜索并找到合适的项目。我面临的问题是它只能用于静态数据。我的数据从RESTful webservice加载。我尝试了多种黑客和技巧,但我无法将Web服务中的数据加载到ng2-select中。看起来这个插件不支持加载Web服务数据。 有没有工作hack加载web服务数据到ng2选择?Angular 2 Select - 从Web服务故障中加载数据
如果不是,请建议一个其他的angular2插件,它可以从web服务加载数据,并允许用户搜索和选择。
更新:
我错过了告诉你我成功地从我的web服务中获取数据。从Web服务获取数据没有问题。问题在于ng2-select。我使用从Web服务获取的数据(由控制台上的印刷物品数组确认)成功填充items
阵列,但ng2-select不显示任何内容。如果我不从Web服务获取数据,只使用本地数据(在初始化时分配)填充数组,它将工作并显示本地数据。
它似乎不能处理请求。以下是评论的示例代码
产品-Category.service.ts
import { Injectable } from '@angular/core';
import { Http} from '@angular/http';
import {Observable} from "rxjs";
@Injectable()
export class ProductCategoryService
{
apiUrl: string = "http://jsonplaceholder.typicode.com/users";
constructor(private http : Http){}
public getUserData(): Observable<any> {
return this.http.get(this.apiUrl)
.map(result => {
return result.json();
});
}
}
产品-category.component.ts
import { Component, OnInit , ViewChild , AfterViewInit , ElementRef } from '@angular/core';
import { Http, Headers , Response , RequestOptions } from "@angular/http";
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'product-category',
templateUrl: 'product-category.component.html',
styles: []
})
export class AddProductCategoryComponent implements OnInit
{
public items = [];
my :boolean= false;
constructor(public productCategoryService:ProductCategoryService){}
ngOnInit()
{
this.getItems();
}
getItems()
{
this.productCategoryService.getUserData().subscribe(
items => this.items
);
}
UPDATE2: 为了简单起见,我附上了一段代码和一张图片以便更好地理解。您可以在代码和图像中看到在从服务器获取响应之后。结果可以在控制台中看到。但为简单起见,我们可以手动添加一个条目到数组中。您可以看到,ng2-select
仅显示发送请求之前填充的数据,但该数组还包含从服务器获取响应后填充的对象。
代码
public items: any = [];
ngOnInit()
{
this.items.push({id : 1 , text : 'Option1'});
this.getItems();
console.log(this.items);
}
getItems()
{
this.productCategoryService.getUserData().subscribe(
success =>
{
this.items.push({id : 2 , text : 'Option2'});
console.log(success);
}
);
}
您可以加入代码 –
请看一看代码 – usmanwalana