【问题标题】:Angular 2 Select - Load data from web service troubleAngular 2 Select - 从 Web 服务问题中加载数据
【发布时间】: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


【解决方案1】:

为此,您可以创建从服务器获取数据的服务

@Injectable()
export class UserService {
  apiUrl: string = "http://jsonplaceholder.typicode.com/users";

  constructor(private http: Http) {
  }


  //getUserData(): Observable<any> {

    //return this.http.get(this.apiUrl)
    //  .map(result => {
    //    return result.json();
    //  });
  //}
  // just for testing use this mechanisum if it working for you or not
  getUserData(): Promise<any[]> {
      return Promise.resolve(ITEMS);
  } 


}

public ITEMS:Array<string> = ['Amsterdam', 'Antwerp', 'Athens', 'Barcelona',
'Berlin', 'Birmingham', 'Bradford', 'Bremen', 'Brussels', 'Bucharest',
'Budapest', 'Cologne', 'Copenhagen', 'Dortmund', 'Dresden', 'Dublin',
'Düsseldorf', 'Essen', 'Frankfurt', 'Genoa', 'Glasgow', 'Gothenburg',
'Hamburg', 'Hannover', 'Helsinki', 'Kraków', 'Leeds', 'Leipzig', 'Lisbon',
'London', 'Madrid', 'Manchester', 'Marseille', 'Milan', 'Munich', 'Málaga',
'Naples', 'Palermo', 'Paris', 'Poznań', 'Prague', 'Riga', 'Rome',
'Rotterdam', 'Seville', 'Sheffield', 'Sofia', 'Stockholm', 'Stuttgart',
'The Hague', 'Turin', 'Valencia', 'Vienna', 'Vilnius', 'Warsaw', 'Wrocław',
'Zagreb', 'Zaragoza', 'Łódź'];

试试这个代码,你会得到 10 个用户数据。这是基本的方式,你可以在Angular 2中调用任何GET api。

将此服务添加到 @NgModule in ap.module.ts 文件中:

@NgModule({
    providers: [UserService]
})

而不是像这样在 Component 类中调用该服务:

items = [];


constructor(private userService: UserService){}

onNgInit(){
   this.getItems();
}

getItems() {
    //this.userService.getUserData().subscribe(
    //   items => this.items;
    //);
    this.userService.getUserData().then(results=> this.items = results);
}



<ng-select [allowClear]="true"
              [items]="items" // here that items will come, but it will be object, i hope in your service you will get Array[] items.
              [disabled]="disabled"
              (data)="refreshValue($event)"
              (selected)="selected($event)"
              (removed)="removed($event)"
              (typed)="typed($event)"
              placeholder="No city selected">
  </ng-select>

【讨论】:

  • 从 Web 服务获取数据没有问题。我仍然测试了你的代码,现在 ng2-select 没有显示任何内容。
  • 能否请您显示您的代码和数据,以便我查看
  • 感谢您对@Vinay 的持续支持。我添加了图像和代码。希望对您有所帮助。
  • 已经用你的 api url 替换了我的代码中的这个 url jsonplaceholder.typicode.com/users? bcz 这个 url 为您提供了 ng2-select 不支持的不同类型的数据。
  • 你在使用 AdminLTE 和 angular 2 吗?你能分享一下你在哪里找到的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 2017-09-28
  • 2016-11-08
  • 1970-01-01
  • 2017-04-16
相关资源
最近更新 更多