【发布时间】:2017-03-24 11:20:13
【问题描述】:
我正在使用ng2-select 显示项目列表,以便用户可以搜索并从选择列表中找到合适的项目。我面临的问题是它只适用于静态数据。我的数据是从 RESTful 网络服务加载的。我尝试了多种黑客和技巧,但我无法将 Web 服务中的数据加载到 ng2-select 中。这个插件似乎不支持加载网络服务数据。 是否有将 Web 服务数据加载到 ng2-select 的有效技巧?
如果不是,请推荐其他 angular2 插件,它可以从 Web 服务加载数据并允许用户搜索和选择。
更新:
我错过了提到我成功地从我的网络服务中获取数据。从 Web 服务获取数据没有问题。问题出在 ng2-select 上。我成功地使用从 Web 服务获取的数据填充了items 数组(由控制台上的打印项数组确认),但 ng2-select 没有显示任何内容。如果我不从 Web 服务获取数据而只使用本地数据(在初始化时分配)填充数组,它会工作并显示本地数据。
它似乎无法处理请求。这是来自评论的示例代码
Product-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();
});
}
}
Product-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
);
}
更新 2:
为简单起见,我附上了代码和图像以便更好地理解。您可以在代码和图像中看到,从服务器获得响应后。结果可以在控制台中看到。但为简单起见,让我们手动在数组中添加一个条目。您可以看到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);
}
);
}
【问题讨论】:
-
你能添加代码吗
-
请看代码
标签: angular jquery-chosen select2 ng2-bootstrap