I'm trying to load some data from a service, the service works as i tested it in the console, it displays the wanted array properly, but when calling the same method of the service from my component (where i need to render the data) it just displays [object Object].... in the console and nothing on the component itself.
FYI : the provider ('/api/departement') that am using works properly since the data can be displayed in the console (data from the service itself).
here's my code :
Department.ts :
export class Departement{
public code_dep:String;
public lib_dep_AR:String;
public lib_dep_FR:String;
public countm:number;
}
Departement.service.ts
import { Departement} from './departement';
import { Http,Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
@Injectable()
export class DepartementService{
constructor(private http:Http){}
private headers = new Headers({'Content-type':'application/json'});
private depUrl = '/api/departement';
getAllDeps():Promise<Departement[]>{
return this.http.get(this.depUrl + "/allDeparts").toPromise().
then(response=>response.json() as Departement[]);
}
// etc
}
displaying.component.ts
export class Displaying implements OnInit {
departements:Departement[];
departement:Departement;
constructor(public depserv:DepartementService,public router:Router) {
}
ngOnInit() {
this.depserv.getAllDeps().then(dep =>
{ this.departements = dep;
});
//etc
}
where i want to render the result
<select name="budget" >
<option>my results down here</option>
<option *ngFor="let x of departements">{{x.lib_dep_FR}}</option>
</select>
fixed by moving on to the Observable interface
Department.service.ts
private extractData(res:Response) {
let body = res.json();
return body || [];
}
getData():Observable<Departement[]>{
return this.http.get(this.depUrl+"/allDeparts").map(this.extractData).catch(this.handleError);
}
catching up the result in the displaying.component.ts
ngOnInit(){
this.depserv.getData().subscribe(
dept => this.departements = dept);
}