usmanwalana
usmanwalana

Reputation: 1062

Angular 2 Select - Load data from web service trouble

I am using ng2-select to display a list of items so that user can search and find the appropriate one from select list. The problem I am facing is that it only works on static data. My data is loaded from RESTful webservice. I have tried multiple hacks and tricks but I am unable to load data from web service into ng2-select. It appears that this plugin does not support loading web service data. Is there a working hack to load webservice data into ng2-select ?

If not please suggest an other angular2 plugin which can load data from web service and enables user to search and select.

Update :
I missed to mention that i am successfully getting data from my web service. There is no issue in getting data from web service. The problem is with ng2-select. I successfully populate the items array with the fetched data from web service(confirmed by printed items array on console) but ng2-select does not show anything. If I do not fetch data from web service and only populate the array with local data(which is assigned at the time of initializing), it works and displays local data.
It Just cant seem to work with requests. Here is an example code from a comment

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

Update2: For simplicity i have attached a code and an image to better understand. You can see in the code and image that after getting a response back from the server. The result can be seen in the console. But for simplicity lets add an entry in the array manually. You can see that ng2-select only displays the data which was populated before sending the request, but the array also contains the object which was populated after getting response back from the server.
Code

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

Image ng2-select

Upvotes: 2

Views: 1984

Answers (1)

Vinay Pandya
Vinay Pandya

Reputation: 3150

for that you can create service which fetches data from your server

@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ź'];

try this code and you will get 10 users data. this is the basic way, you can call any GET api in Angular 2.

add this service to @NgModule in ap.module.ts file:

@NgModule({
    providers: [UserService]
})

than call that service in Component class like this:

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>

Upvotes: 1

Related Questions